import errorMessage from 'share/errorMessage'
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import {messages, getApprovelHistory, queryCurrencyPrecision, deepFullCopy, removeToken} from 'share/common'
import lowCarbonTravel from "images/request/travel/low-carbon-travel.jpg"
import {
  Form,
  Alert,
  Affix,
  Button,
  Spin,
  Icon,
  Modal,
  message,
  Popconfirm,
  Switch,
  Select,
  Row,
  Col,
  Progress,
  Tabs,
  Timeline,
  DatePicker,
  Popover,
  Tooltip
} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
import chooserData from 'share/chooserData'

import config from 'config'
import moment from 'moment'
import constants from 'share/constants'
import TravelDate from 'containers/request/travel-request/travel-date'
import TravelType from 'containers/request/travel-request/travel-type';
import TravelElementType from 'containers/request/travel-request/travel-element-type';
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import RelatedApplication from 'containers/request/new-request/related-application'
import customField from 'share/customField'
import baseService from 'share/base.service'
import requestService from 'containers/request/request.service'
import TravelPreviousVersion from 'containers/request/travel-request/travel-previous-version'
import ExpectStopDate from 'containers/request/travel-request/expect-stop-date'
import ApproveHistory from 'components/template/approve-history'
import ExpenseTypeModal from 'containers/request/new-request/expense-type-modal'
import Chooser from 'components/chooser'
import 'styles/request/new-request.scss'
import debounce from 'lodash.debounce'
import BudgetExplain from 'components/template/budget-explain/budget-explain'

import approveRequestService from 'containers/approve/request/request.service'
import subsidyService from "../expense-report/template/subsidy-service";
import { GiftDeclare, GiftDeclareTitle } from './gift-declare/gift-declare'
import giftDeclareService from './gift-declare/gift-declare-service'
import { setGiftDeclareValue, getGiftDeclareValue } from './gift-declare/gift-declare-utils'
import GreenCode from "containers/request/greencode/green-code";
import ReactIF from "components/UI/ReactIF";
import {setDocumentaryCompany} from "actions/login";
import mainService from "containers/main.service";
let newRequestThis;
let firstInitLoad;
class NewRequest extends React.Component {
  travelParams = {};//差旅申请单提交或保存的参数
  percentNum = 0;//进度条变化基数
  canGo = true;//是否可进入修改头部数据弹框提示操作
  isReplace = false;//是否替换参与人
  isSetCloseEnabled = false;//是否设置了停用日期
  closeDate = "";//预计停用日期
  closeDay = 0; //差旅结束后多少天自动停用
  isSubsidySave = false;//是否是因为要添加差补而要保存当前单据
  noChangePar = false;//是否改动申请人了且币种也变化了
  customFormFieldsOrigin = {};// 表单配置原始值。（每次获取都是最新配置值，不许改变）
  constructor(props) {
    super(props);
    newRequestThis = this;
    firstInitLoad = false;
    this.state = {
      formDate:[],
      isHR: false,//是否是hr人员
      loading: false,
      isSwitchOn: false,//联动开关
      saveLoading: false, //保存按钮
      submitLoading: false, //提交按钮
      deleteLoading: false, //删除按钮
      autoLoanLoading: false, //去借款按钮
      jobId: '', //单据岗位id
      jobInfo: {}, //岗位信息
      info: {}, //申请单详情
      thirdPartyInfo: {}, //第三方返回信息
      warningList: [], //预算校验结果
      formInfo: {}, //表单详情
      originalFormInfo: {}, // 原始表单详情
      formDefaultValue: [], //表单默认值
      formType: null,
      defaultValues: [],
      copyDefaultValues: [],
      valuesOnlyForShow: [], //差旅单编辑状态的custFormValues
      isHasTravelBudgetDetail: false, //申请单是否配置了预算明细控件，差旅单，费用单都适用
      travelBudgetDetailObj: null, //差旅单的预算明细控件的对象
      // 废弃applicationList, 请使用menuRoute.goBack(this)返回申请单列表页
      // applicationList: menuRoute.getRouteItem(`${this.props.location.pathname.split('/')[2]}`, 'key'), //申请单列表页
      subsidyCtrl: {
        flight: false,//是否显示飞机统一订票
        flightPlatform: false, //机是否有支持订票平台的机票行程
        train: false,//。。。。火车统一订票
        hotel: false,//是否显示酒店统一订票
        dining: false, //是否显示用餐统一订票
        didi: false, //是否显示用车统一订票 用车只有各自订票
        isBudgetCheck: false,//是否进行预算校验
        platformPerson: [], //订票专员选择范围
        selectPerson: [],//被选择的统一订票人（创建人+申请人+参与人）
        itineraryRequire: false,//提交时是否必须添加行程
      },//差旅申请单提交时检验控制量
      isShowModal: false,//是否显示统一订票弹框
      maxFlight: {},//最大机票数接口返回数据
      maxHotel: {},//最大房间数接口返回数据
      randomHotel: false,//随机生成酒店合住人
      isFlight: true,//是否使用飞机统一订票
      isFlightSwitch: true, //是否显示飞机统一订票的切换开关
      isTrain: true,//是否使用火车统一订票
      isTrainSwitch: true, //是否显示火车统一订票的切换开关
      isHotel: true,//是否使用酒店统一订票
      isHotelSwitch: true, //是否显示酒店统一订票的切换开关
      isDining: true,//是否使用用餐统一订票
      isDiningSwitch: true, //是否显示用餐统一订票的切换开关
      percent: 0,//预算校验进度数值
      budgeting: false,//是否弹框提示预算校验进度
      totalBudget: 0,//差旅总金额
      total: 0,//差补总金额
      amount: 0,//预算明细总金额
      haveClear: false,//是否清空差补
      isFirstSave: false, //是否是新建的保存，如果是，需要判断自动差补逻辑
      isHaveRoute: false,//是否有行程存在
      isRepeatSubsidy: false,//是否有重复差补明细
      defaultRelativeApplication: undefined, //默认关联申请单
      referenceApplicationOID: '', //关联申请单OID
      approvalHistory: [], //审批历史
      isHaveSubsidyRules: false,//是否设置了差补规则
      subsidyRulesFieldOID: [],//设置了差补规则的fieldOID
      signEnable: false, //是否可以加签
      signReset: true, //是否重置加签
      participantChanged: false, //是否手动改了参与人
      formIsChange: false,//表单是否已经改动且未保存
      currentCodeType: props.company.baseCurrency,//当前总金额币种
      isControlRangeDate: false, //是否控制出差日期范围
      hotelStartFloatDays: 0, //酒店入住日期的浮动天数
      hotelEndFloatDays: 0, //酒店离店日期的浮动天数
      hotelOffStartFloatDays: 0, //酒店入住日期的浮动天数
      hotelOffEndFloatDays: 0, //酒店离店日期的浮动天数
      itineraryData: {}, //用于校验日期范围的机票，火车，酒店行程
      isShowRangePicker: false, //是否展示日期连选
      travelElement: false,
      travelElementsList: [],
      travelElementServiceName: '', //差旅要素 表头供应商控件的serviceName
      travelItinerarys: [], //差旅要素的行程信息
      manageType: false,
      dateChage: true,
      signCompanyOIDs: [],//加签人公司范围
      editTicketInfoVisible: false, //是否显示编辑行程信息：若是新建差旅申请单默认不显示，编辑默认显示
      userInfoCheckVisible: false, //校验人员证件信息的结果弹框
      showSubmitBtn: true, // 是否显示提交按钮
      userCheckResult: '',
      tabKey: 'requestInfo',
      isProxy: false, //是否是代理别人制单
      budgetExplainNumber: 0, //预算执行情况列表数量
      isSaveBtnClicked: false, //编辑页点的是保存按钮吗
      needClearSubsidy: false, //是否需要在点击保存按钮时清空差补
      requestEditDetail: menuRoute.getRouteItem('business-and-gift-application-giftDetail', 'key'), // 礼品申请单详情页
      isCustListSwitch: false,
      principalOID: undefined,
      userIsHr: false,
      hrInfo: undefined,
      thirdUserEid: undefined,
      fafangleixingFlag: false
    };
    this.state.copyDefaultValues.checkedChange = this.checkedChange;
    this.state.copyDefaultValues.expectStopDate = this.expectStopDate;
    this.state.copyDefaultValues.checkedOk = this.checkedOk; //日期连选确定的回调
    this.handleUserCheckModal = debounce(this.handleUserCheckModal, 500);
    this.newLoan = menuRoute.getRouteItem('new-borrow', 'key'); //新建单行、多行借款单
    this.editLoan = menuRoute.getRouteItem('edit-borrow', 'key'); //单行借款单编辑页
    this.loanDetail = menuRoute.getRouteItem('loan-detail', 'key'); //多行借款单编辑页，单行&多行非编辑详情页
  };

  //formValueOID 编辑状态表单的key值设置

  /**
   * 预计停用日期的回调函数
   * @param isSet 是否设置了预计停用日期
   * @param closeDate 设置的具体日期
     */
  expectStopDate = (isSet, closeDate) => {
    this.isSetCloseEnabled = isSet;
    this.closeDate = closeDate;
  }

  /**
   * 部分表单控件value值变化监听函数
   * @param field 表单项
   * @param value 控件value值（某一个对象的某一个属性值），
   * @param allValue 控件完整值（整个对象或者数组），
   * @param from 事件触发的地方 主要检查参与人的清空按钮和弹框的确定按钮（string）
     */
  checkedChange = (field, value, allValue, from) => {
    console.log('部分表单控件value值变化监听函数')
    const { enableDepCompany } = this.props;
    let copy = this.state.copyDefaultValues;
    let travelBudgetDetailObj = this.state.travelBudgetDetailObj;
    let isChangeCompany = false;
    let isChangeOwner = false;
    let isChangeDepartment = false;
    let isChangeCurrency = false;
    let oldCurrencyCode = null;
    let isChangeFatherCostCenter = false;
    let isChangeParticipant = false;
    let isChangeStar = false;
    let isChangeApprover = false;
    let isChangeOverseas = false;
    let isChangeDepartmentFlag = false;
    let isChangeKq = false;
    let { formInfo, defaultValues } = this.state;
    let custForm = this.props.params.applicationOID ? defaultValues || [] : formInfo.customFormFields || [];
    let id = this.props.params.applicationOID ? 'formValueOID' : 'fieldOID';
    const { formCode } = formInfo;
    copy.map(res => {
      if ((res.messageKey === field.messageKey) && value !== res.value && (res.fieldOID === field.fieldOID) && field.fieldCode === 'kq') {
        isChangeKq = true;
      }
      if ((res.messageKey === field.messageKey) && value !== res.value && (res.fieldOID === field.fieldOID) && (field.messageKey === 'select_cost_center' || field.messageKey === 'select_department')) {
        res.showName = allValue;
        res.value = value;
        if (field.messageKey === 'select_cost_center' && field.dataSource && JSON.parse(field.dataSource || '{}').type !== 'father' && formCode === 'SQ002' && field.fieldName === '费用承担部门') {
          isChangeDepartmentFlag = true
        }
        if (field.messageKey === 'select_cost_center' && field.dataSource && JSON.parse(field.dataSource || '{}').type === 'father') {
          isChangeFatherCostCenter = true;
        }
        if (field.messageKey === 'select_department' && !(field.fieldConstraint && JSON.parse(field.fieldConstraint).valueReadonly)) {
          // task#36497
          // 问题：新建申请单时触发了此逻辑，导致成本中心清空了
          // 解决：加上只读的限制，允许编辑时才触发此逻辑
          isChangeDepartment = true;
        }
      }
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID && field.messageKey === 'select_company') {
        isChangeCompany = true;
        res.value = value;
      }
      if (res.messageKey === field.messageKey && value !== res.value && res.fieldOID === field.fieldOID && field.messageKey === 'currency_code') {
        isChangeCurrency = true;
        oldCurrencyCode = res.value;
        res.value = value;
      }
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID && field.messageKey === 'select_participant' && formCode === 'MCD3001') {
        isChangeParticipant = true;
        // res.value = value;
      }
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID && field.fieldCode === 'star' && formCode === 'MCD3001') {
        isChangeStar = true;
      }
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID && field.fieldCode === 'overseas' && ['MCD2001', 'MCD5001'].indexOf(formCode) > -1) {
        isChangeOverseas = true;
      }
    });
    let fieldConstraint = JSON.parse(field.fieldConstraint || '{}')
    const _this = this
    if (isChangeCompany && fieldConstraint.unionCompany && value.length > 0) {
      requestService.getCostcenterByCompany(value[0].companyOID).then((res) => {
        if (res.data) {
          copy.map(item => {
            if (item.messageKey === 'select_cost_center') {
              item.showName = res.data.name;
              item.value = res.data.costCenterItemOID;
              if (_this.props.params.applicationOID) {
                _this.props.form.setFieldsValue({ [item.formValueOID]: [{ costCenterItemOID: String(res.data.costCenterItemOID), name: res.data.name }] });
              } else {
                _this.props.form.setFieldsValue({ [item.fieldOID]: [{ costCenterItemOID: String(res.data.costCenterItemOID), name: res.data.name }] });
              }
            }
          });
        } else {
          copy.map(item => {
            if (item.messageKey === 'select_cost_center') {
              item.showName = undefined;
              item.value = '';
              if (_this.props.params.applicationOID) {
                _this.props.form.setFieldsValue({ [item.formValueOID]: [{ costCenterItemOID: undefined, name: '' }] });
              } else {
                _this.props.form.setFieldsValue({ [item.fieldOID]: [{ costCenterItemOID: undefined, name: '' }] });
              }
            }
          });
        }
      }).finally(() => {
        this.setState({ loading: false });
      });
    } else {
      //切换了公司.或者切换部门都要查询是否要清空成本中心，切公司额外要看是否清空部门
      if (isChangeCompany || isChangeDepartment) {
        this.setState({ loading: true });
        requestService.checkCostCenterNeedEmpty().then(res => {
          //res.data为true说明要清空成本中心项
          if (res.data && res.data.visible) {
            let setData = {};
            let fieldOID = ''
            custForm.map(i => {
              if (i.messageKey === 'select_cost_center' || i.messageKey === 'select_user') {
                setData[i[id]] = undefined;
                if (i.messageKey === 'select_cost_center' && i.fieldName === '费用承担部门') {
                  fieldOID = i.fieldOID
                }
              }
            });
            this.props.form.setFieldsValue(setData);
            copy.map(item => {
              if (item.messageKey === 'select_cost_center') {
                item.showName = undefined;
                item.value = '';
              }
            });
            let {formDefaultValue} = this.state
            formDefaultValue = formDefaultValue.map(item => {
              if (item.fieldOID === fieldOID) {
                item.value = ''
                item.name = ''
              }
              return item
            })
            this.setState({
              formDefaultValue,
              copyDefaultValues: copy
            })
          }
        }).finally(() => {
          this.setState({ loading: false });
        });

        //为open表示部门关联公司开启，则切换公司要清空部门
        if (isChangeCompany && enableDepCompany === 'OPEN') {
          let setData = {};
          custForm.map(i => {
            if (i.messageKey === 'select_department') {
              setData[i[id]] = undefined;
            }
          });
          this.props.form.setFieldsValue(setData);
          copy.map(item => {
            if (item.messageKey === 'select_department') {
              item.showName = undefined;
              item.value = '';
            }
          });
        }
      }
    }
    //切换了父成本中心要清空子成本中心项
    if (isChangeFatherCostCenter) {
      let setData = {};
      custForm.map(i => {
        if (i.messageKey === 'select_cost_center' && i.dataSource && JSON.parse(i.dataSource || '{}').type === 'son') {
          setData[i[id]] = undefined;
        }
      });
      this.props.form.setFieldsValue(setData);
      copy.map(item => {
        if (item.messageKey === 'select_cost_center' && item.dataSource && JSON.parse(item.dataSource || '{}').type === 'son') {
          item.showName = undefined;
          item.value = '';
        }
      });
    }
    if (isChangeCurrency) {
      //判断是否有预算明细费用，费用申请单和差旅申请单的判断方法不同
      let isHasExpense = false;
      let setDataBudgetKey = null; //预算明细控件在values中的key值
      let setDataCurrencyKey = null; //币种控件在values中的key值
      custForm.map(i => {
        //费用申请单在这判断
        if (i.messageKey === 'budget_detail' && i.value && JSON.parse(i.value)
          && JSON.parse(i.value).budgetDetail && JSON.parse(i.value).budgetDetail.length && this.state.formType !== 2001) {
          isHasExpense = true;
          setDataBudgetKey = i[id];
        }
        if (i.messageKey === 'currency_code') {
          setDataCurrencyKey = i[id];
        }
      });
      //差旅申请单在这判断
      if (travelBudgetDetailObj && travelBudgetDetailObj.budgetDetail && travelBudgetDetailObj.budgetDetail.length) {
        isHasExpense = true;
      }
      if (isHasExpense) {
        //弹框提示是否继续修改币种
        Modal.confirm({
          title: messages('request.key173'/*提示*/),
          content: <div>
            <p>{messages('request.key549')/*修改币种会清除已填写的预算明细，是否继续？*/}</p>
          </div>,
          okText: messages('common.ok')/*确认*/,
          cancelText: messages('request.key175'/*取消*/),
          onOk: () => this.handleChangeCurrency(copy, setDataBudgetKey),
          onCancel: () => this.cancelChangeCurrency(copy, setDataCurrencyKey, oldCurrencyCode)
        });
      } else {
        this.setState({ copyDefaultValues: copy });
      }
    } else {
      this.setState({ copyDefaultValues: copy });
    }

    //申请人改变
    if (field.messageKey === 'applicant' && this.state.formType !== 2001) {
      // 单独处理
      this.isReplace = true;
      //参数中使用{value：data.value},而不是直接使用 data，是因为data是数组copyDefaultValue的一个项，当该项
      //被更新后，传入的值也就改变了，即会出现传入时是a,某一时刻就变成copyDefaultValue更新后的值b了
      this.soveApplicant({ value }, { value: this.state.copyDefaultValues[0].value }, true);
      if (this.state.total > 0)
        this.clearSubsidy();
      //更新副本中的默认值
      this.updateCopyDefaultValue(0, { value });
    }

    //参与人改变
    if (isChangeParticipant) {
      console.log('参与人改变', from)
      //task#30329 【交付-麦当劳】团体申请单的选人审批进行人员过滤 -- 参与人改变，清空自选审批人
      if (from) {
        this.setState({ signReset: false, participantChanged: true }, () => {
          this.setState({ signReset: true });
        });
        custForm.map(i => {
          // 参与人改变的话，将参与人控件的showValue置空，否则重新render时，getInitialValue会设置成原先的参与人值，导致参与人无法清空
          if (i.messageKey === 'select_participant' /*&& i.value !== JSON.stringify(value)*/) {
            i.showValue = i.value = JSON.stringify(value);
          }
        });
      }
      // this.props.form.setFieldsValue({
      //   'addSign': []
      // });

      //task#34001: 根据【参与人】和【酒店星级】自动计算最大房间数（团体申请单）
      this.computeMaxNum(custForm, value);
    }

    //酒店星级改变
    if (isChangeStar) {
      console.log('酒店星级改变')
      //task#34001: 根据【参与人】和【酒店星级】自动计算最大房间数（团体申请单）
      this.computeMaxNum(custForm, null, value);
    }

    //国际（含香港）差旅申请单--出差地改变
    if (isChangeOverseas) {
      console.log('出差地改变')
      //task#38635：国际（含香港）差旅申请单 出差地-目的地香港赋值
      let overseasVal = '';
      let toId = '';
      let toField;
      custForm.map(i => {
        if (i.fieldCode === 'overseas') { // 出差地
          overseasVal = this.props.form.getFieldValue(i[id]);
        } else if (i.fieldCode === 'to') {
          toId = i[id];
          toField = i;
        }
      });
      if (value === 'MCD1001') { // 出差地香港
        this.handleToCity(toId, toField, allValue);
        this.setToFieldDisable(custForm, true);
      } else {
        this.setToFieldDisable(custForm, false);
      }
    }
    // 根据卡券类型展示发放类型字段
    if(isChangeKq){
      if (allValue && allValue.id) {
        if(value==='001'){ //选择实体卡券
          this.setState({fafangleixingFlag:false})
        } else if(value==='002') {
          this.setState({fafangleixingFlag:true})
          custForm.map((i)=> {
            if (i.fieldCode === 'fafangleixing') {
              i.required = true;
              i.valid = true;
            }
          });
        } else { //没有选择类型不展示发放类型
          this.setState({fafangleixingFlag:false})
          }
      }else { //默认不展示发放类型
        if(formCode === 'SQ002' && value === '001'){
          this.setState({fafangleixingFlag:false})
        }
      }
    }

    // 礼品申请单修改费用承担部门时清空费用确认人以及修改选择费用确认人的入参
    if (isChangeDepartmentFlag) {
      if (allValue && allValue.id) {
        let {formDefaultValue} = this.state
        let findIndex = formDefaultValue.findIndex(item => item.fieldOID === field.fieldOID)
        if (findIndex === -1) {
          formDefaultValue.push({
            fieldName: field.fieldName,
            fieldOID: field.fieldOID,
            name: allValue.name,
            showValue: allValue.name,
            value: value
          })
        } else {
          formDefaultValue = formDefaultValue.map(item => {
            if (item.fieldOID === field.fieldOID) {
              item.value = value
              item.name = allValue.name
            }
            return item
          })
        }
        let setData = {};
        custForm.map(i => {
          if (i.messageKey === 'select_user') {
            setData[i[id]] = undefined;
          }
        });
        this.props.form.setFieldsValue(setData);
        this.setState({
          formDefaultValue
        })
      } else if (!allValue) {
        let {formDefaultValue} = this.state
        formDefaultValue = formDefaultValue.map(item => {
          if (item.fieldOID === field.fieldOID) {
            item.value = ''
            item.name = ''
          }
          return item
        })
        let setData = {};
        custForm.map(i => {
          if (i.messageKey === 'select_user') {
            setData[i[id]] = undefined;
          }
        });
        this.props.form.setFieldsValue(setData);
        this.setState({
          formDefaultValue
        })
      }
    }
  };

  handleToCity = (toId, toField, allValue) => {
    const { language } = this.props;
    let country = 'china';
    let keyword = allValue.messageKey;
    let data = [];
    let values = [];
    let setData = {};
    subsidyService.searchCites(keyword, country, language.code === 'zh_cn' ? 'zh_cn' : 'en_us').then(res => {
      data = res.data || [];
      data.map(item => {
        values.push({
          label: item.adName,
          key: item.adCode
        })
      });
      setData[toId] = JSON.parse(toField.fieldContent || '{}').type === '1' ? values : (values[0] ? { adName: values[0].label, adCode: values[0].key } : undefined);
      this.props.form.setFieldsValue(setData); // 设置目的地香港
    });
  };

  //详情页设置申请人控件不可更改
  setToFieldDisable = (fields, isReadOnly) => {
    fields.map(item => {
      if (item.fieldCode === 'to') {
        item.isReadOnly = isReadOnly;
      }
    });
  };

  /**
   * 根据参与人自动计算最大房间数
   * @param field 表单项
   * @param participant 参与人value值，
   * @param star 酒店星级
   */
  computeMaxNum = (custForm, participant, star) => {
    let id = this.props.params.applicationOID ? 'formValueOID' : 'fieldOID';
    let maxnum = null;
    let setData = {};
    let maxNumId = '';
    let starId = '';
    let participantsId = '';

    custForm.map(i => {
      if (i.fieldCode === 'maxnum') { // 最大房间数
        maxNumId = i[id];
      }
      if (i.fieldCode === 'star') { // 酒店星级
        starId = i[id];
      }
      if (i.fieldCode === 'participants') { // 参与人
        participantsId = i[id];
      }
    });

    if (!starId || !participantsId || !maxNumId) return;

    let starVal = star || this.props.form.getFieldValue(starId);
    let participantsVal = participant || this.props.form.getFieldValue(participantsId);
    console.log(starVal, participantsVal);
    // 计算最大房间数 -- 酒店星级必填！
    let maleNum = 0;
    let femaleNum = 0;
    if (starVal && participantsVal && participantsVal.length) {
      let maleArr = [];
      let femaleArr = [];
      // 先按性别分组
      participantsVal.map(p => {
        p.gender === 0 && maleArr.push(p);
        p.gender === 1 && femaleArr.push(p);
      });
      maleNum = this.handleMazNumBySex(maleArr, starVal);
      femaleNum = this.handleMazNumBySex(femaleArr, starVal);
      maxnum = maleNum + femaleNum;
    }
    setData[maxNumId] = maxnum;
    this.props.form.setFieldsValue(setData);
  };

  handleMazNumBySex = (orgArr, starVal) => {
    if (!orgArr.length) return 0;
    //O4C、P4、O4B、O4A、P3、P2、P1、Crew1、Crew2、Crew3、CrewA2、ETSMT、SMTMT、SMTRDM、SMTRGM、SMTRPM
    // const rankCodes = ['Ops', 'Finance', 'Restaurant'];
    const rankCodes = ['O4C', 'P4', 'O4B', 'O4A', 'P3', 'P2', 'P1', 'Crew1', 'Crew2', 'Crew3', 'CrewA2', 'ETSMT', 'SMTMT', 'SMTRDM', 'SMTRGM', 'SMTRPM'];
    //O5B、P6、M2、O5A、P5、M1
    // const rankCodeNew = ['Manager'];
    const rankCodeNew = ['O5B', 'P6', 'M2', 'O5A', 'P5', 'M1'];
    const newArr1 = [];
    const newArr2 = [];
    const newArr3 = [];
    let result = 0;
    orgArr.map(m => {
      // 还要按级别分组
      if (!m.rankCode || rankCodes.indexOf(m.rankCode) > -1) { // 级别在rankCodes中的男/女性
        newArr1.push(m);
      } else if (rankCodeNew.indexOf(m.rankCode) > -1) { // 级别在rankCodeNew中的男/女性
        newArr3.push(m);
      } else { // 级别不在rankCodes、rankCodeNew中的男/女性
        newArr2.push(m);
      }
    });

    const newArr1Len = newArr1.length;
    const newArr2Len = newArr2.length;
    const newArr3Len = newArr3.length;
    // 级别在rankCodes中时，无论酒店星级如何，必须两人一间
    newArr1Len && (result += (newArr1Len / 2));
    // 级别在rankCodeNew中时，当酒店星级为4星及以下时，为1人一间；当酒店星级为非4星及以下时，必须两人一间
    newArr3Len && (result += ((starVal === '2001') ? newArr3Len : (newArr3Len / 2)));
    // 级别不在rankCodes、rankCodeNew中时，1人一间
    newArr2Len && (result += newArr2Len);
    return Math.ceil(result);
  };

  //确认修改币种
  handleChangeCurrency = (copyValue, setDataKey) => {
    this.setState({
      copyDefaultValues: copyValue,
      travelBudgetDetailObj: null
    });
    if (this.state.formType !== 2001) {
      this.props.form.setFieldsValue({ [setDataKey]: undefined });
    }
  };

  //取消修改币种
  cancelChangeCurrency = (copyValue, setDataKey, oldCurrency) => {
    copyValue.map(item => {
      if (item.messageKey === 'currency_code') {
        item.value = oldCurrency;
      }
    });
    this.setState({ copyDefaultValues: copyValue });
    this.props.form.setFieldsValue({ [setDataKey]: oldCurrency });
  };

  componentWillMount() {
    const { params } = this.props;
    if (params.applicantOID && params.applicantOID !== ':applicantOID') {
      this.setState({ isProxy: true });
      baseService.changeLoginInfo(this.props.params.applicantOID).then(() => {

      }).catch(() => {
        message.error(messages('request.key169'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/)); //呼，服务器出了点问题，请联系管理员或稍后再试:(
      });
    }
    if (params.jobId && params.jobId !== ':jobId') {
      this.setState({ jobId: params.jobId }, this.getJobInfo);
    }
  }

  // 获取间隔天数
  getDays = (day1, day2) => {
    let travelItinerarys = [];
    // 获取入参字符串形式日期的Date型日期
    let strArr = moment(day1).format('YYYY-MM-DD').split('-');
    let d1 = new Date(strArr[0], strArr[1] - 1, strArr[2]);
    let strArr2 = moment(day2).format('YYYY-MM-DD').split('-');
    let d2 = new Date(strArr2[0], strArr2[1] - 1, strArr2[2]);
    // 定义一天的毫秒数
    let dayMilliSeconds = 1000 * 60 * 60 * 24;

    // 获取输入日期的毫秒数
    let d1Ms = d1.getTime();
    let d2Ms = d2.getTime();

    // 定义返回值
    let ret = [];

    // 对日期毫秒数进行循环比较，直到d1Ms 大于等于 d2Ms 时退出循环
    // 每次循环结束，给d1Ms 增加一天
    for (d1Ms; d1Ms <= d2Ms; d1Ms += dayMilliSeconds) {

      // 如果ret为空，则无需添加","作为分隔符
      if (!ret) {
        // 将给的毫秒数转换为Date日期
        let day = new Date(d1Ms);

        // 获取其年月日形式的字符串
        ret = moment(day).format('YYYY-MM-DD');
      } else {

        // 否则，给ret的每个字符日期间添加","作为分隔符
        let day = new Date(d1Ms);
        ret.push(moment(day).format('YYYY-MM-DD'));
        travelItinerarys.push({
          itineraryDate: moment(day).utc().format(),
          travelElements: [],
          travelItineraryTraffics: []
        })
      }
    }

    //存入已经选好存在的时间段的行程
    travelItinerarys.map((item, index) => {
      //moment(item.itineraryDate).format('YYYY-MM-DD')
      this.state.travelItinerarys.map((oldItem, oldIndex) => {
        if (moment(item.itineraryDate).format('YYYY-MM-DD') === moment(oldItem.itineraryDate).format('YYYY-MM-DD')) {
          travelItinerarys[index] = this.state.travelItinerarys[oldIndex]
        }
      })
    });
    this.setState({
      dateChage: false,
      travelItinerarys: travelItinerarys
    }, () => {
      this.setState(({
        dateChage: true,
      }))
    });
    // alert(ret); // 或可换为return ret;
  }



  //日期连选控件打开或者关闭的时候的回调
  checkedOk = (field, value) => {
    const { formType } = this.state;
    this.canGo = false;
    let formInfo = this.props.params.applicationOID ? this.state.info : this.state.formInfo;
    let copy = this.state.copyDefaultValues;
    let startDate = null;
    let endDate = null;
    setTimeout(() => {
      //value为false表示关闭日期弹框
      if (!value && field.value) {
        startDate = field.value.split('\"')[1];
        endDate = field.value.split('\"')[3];
        if (field.enableTime) {
          startDate = moment(startDate).second(0).utc().format();
          endDate = moment(endDate).second(0).utc().format();
        } else {
          startDate = moment(startDate).format('YYYY-MM-DD');
          endDate = moment(endDate).format('YYYY-MM-DD');
        }

        if (this.isSetCloseEnabled) {
          this.closeDate = moment(endDate).add(this.closeDay, 'days');
        }

        //赋值到start_date,end_date控件
        if (this.props.params.applicationOID) {
          this.refreshRangeDate(formInfo.custFormValues, startDate, endDate);
          this.setState({
            info: formInfo
          }, () => {
            this.judgeDateChange(startDate, endDate, field.enableTime);
          });
        } else {
          this.canGo = true;
          this.refreshRangeDate(copy, startDate, endDate);
          this.refreshRangeDate(formInfo.customFormFields, startDate, endDate);
          this.setState({
            formInfo: formInfo,
            copyDefaultValues: copy
          });
          formType === 2001 && this.getDays(startDate, endDate);
        }
      }
    }, 500);
  };

  //校验日期是否有变化，如果变化了是否弹窗提示删差补，只适用ranger_picker的情况
  //enableTime是否启用时间
  judgeDateChange = (startDate, endDate, enableTime) => {
    const { isHaveRoute, manageType, formType } = this.state;
    let formInfo = this.state.info;
    let isChange = false;//日期是否变化
    let isShowModal = false;//是否需要弹框提示
    if (this.props.params.applicationOID) {
      formInfo.custFormValues.map((item, index) => {
        if (item.messageKey === 'start_date' || item.messageKey === 'end_date') {
          let baseStartData = this.state.copyDefaultValues[index];
          if (baseStartData && baseStartData.value !== item.value) {
            isChange = true;
            //增加旧差旅行程提示
            if ((isHaveRoute || !manageType) && formType === 2001) {
              //差旅单才可能有这个弹框提示，费用单没有
              isShowModal = true;
            }
          }
        }
      });
    }

    if (isShowModal) {
      let isItineraryDateOK = this.judgeItineraryDateRange(startDate, endDate, enableTime);
      //true校验通过，false校验不通过
      let currentKey = 'virtual_range_picker';
      if (isItineraryDateOK) {
        let isHaveSubsidy = this.state.total > 0;
        let fieldStr = messages('request.key170'/*出差往返日期*/);
        let mesStr = '';
        let mesSubsidy = '';
        //如果没有配置行程强校验，走原来弹框提示
        if (!this.state.isControlRangeDate) {
          // mesStr = messages('request.key452',{arg1: fieldStr}/*更改{arg1}可能导致行程与出差日期不匹配*/);
          mesSubsidy = isHaveSubsidy ? messages('request.key453', { arg1: fieldStr }/*更改{arg1}将清空已添加差补*/) : '';
          mesSubsidy && this.baseModalShowForRangeDateChange(mesSubsidy, mesStr, currentKey, startDate, endDate);
        }
        //如果配置了行程强校验，根据是否有差补来决定是否弹框提示
        if (this.state.isControlRangeDate) {
          if (isHaveSubsidy) {
            mesSubsidy = isHaveSubsidy ? messages('request.key453', { arg1: fieldStr }/*更改{arg1}将清空已添加差补*/) : '';
            mesSubsidy && this.baseModalShowForRangeDateChange(mesSubsidy, mesStr, currentKey, startDate, endDate);
          } else {
            this.processDateChange(startDate, endDate);
          }
        }
      } else {
        this.baseModalDisableDateChange(currentKey);
      }
    } else {
      if (isChange) {
        let copy = this.state.copyDefaultValues;
        this.refreshRangeDate(copy, startDate, endDate);
        this.setState({
          formIsChange: true,
          copyDefaultValues: copy
        }, () => {
          this.canGo = true;
        });
      } else {
        this.canGo = true;
      }
      formType === 2001 && this.getDays(startDate, endDate);
    }
  };

  //校验改变后的日期是否包含行程日期范围
  judgeItineraryDateRange = (startDate, endDate, enableTime) => {
    if (this.state.isControlRangeDate) {
      let start = startDate;
      let end = endDate;
      //不管是否启用时间，都按零点时间计算
      start = moment(start).hours(0).minutes(0).seconds(0).utc().format();
      end = moment(end).hours(23).minutes(59).seconds(59).utc().format();
      //校验机票行程日期范围
      if (this.state.itineraryData && this.state.itineraryData.FLIGHT && this.state.itineraryData.FLIGHT.length) {
        let flightItinerary = this.state.itineraryData.FLIGHT;
        let isFlightOK = true;
        flightItinerary.map(flight => {
          if (flight.startDate && !this.judgeSubset(start, end, flight.startDate)) {
            isFlightOK = false;
          }
          if (flight.endDate && !this.judgeSubset(start, end, flight.endDate)) {
            isFlightOK = false;
          }
        });
        if (!isFlightOK) {
          return false;
        }
      }
      //校验智能机票行程日期范围
      if (this.state.itineraryData && this.state.itineraryData.AUTO_FLIGHT && this.state.itineraryData.AUTO_FLIGHT.length) {
        let autoFlightItinerary = this.state.itineraryData.AUTO_FLIGHT;
        let isFlightOK = true;
        autoFlightItinerary.map(flight => {
          if (flight.startDate && !this.judgeSubset(start, end, flight.startDate)) {
            isFlightOK = false;
          }
          if (flight.endDate && !this.judgeSubset(start, end, flight.endDate)) {
            isFlightOK = false;
          }
        });
        if (!isFlightOK) {
          return false;
        }
      }
      //校验火车行程日期范围
      if (this.state.itineraryData && this.state.itineraryData.TRAIN && this.state.itineraryData.TRAIN.length) {
        let trainItinerary = this.state.itineraryData.TRAIN;
        let isTrainOK = true;
        trainItinerary.map(train => {
          if (train.startDate && !this.judgeSubset(start, end, train.startDate)) {
            isTrainOK = false;
          }
        });
        if (!isTrainOK) {
          return false;
        }
      }
      //校验酒店行程日期范围，要考虑浮动日期
      if (this.state.itineraryData && this.state.itineraryData.HOTEL && this.state.itineraryData.HOTEL.length) {
        let hotelItinerary = this.state.itineraryData.HOTEL;
        let isHotelOK = true;
        let startHotel = moment(start).subtract(this.state.hotelStartFloatDays, 'days').utc().format();
        let endHotel = moment(end).add(this.state.hotelEndFloatDays, 'days').utc().format();
        hotelItinerary.map(hotel => {
          if (hotel.fromDate && !this.judgeSubset(startHotel, endHotel, hotel.fromDate)) {
            isHotelOK = false;
          }
          if (hotel.leaveDate && !this.judgeSubset(startHotel, endHotel, hotel.leaveDate)) {
            isHotelOK = false;
          }
        });
        if (!isHotelOK) {
          return false;
        }
      }

      //校验非TMC酒店行程日期范围，要考虑浮动日期
      if (this.state.itineraryData && this.state.itineraryData.OFFLINE_HOTEL && this.state.itineraryData.OFFLINE_HOTEL.length) {
        let hotelItinerary = this.state.itineraryData.OFFLINE_HOTEL;
        let isOfflineHotelOK = true;
        let startOfflineHotel = moment(start).subtract(this.state.hotelOffStartFloatDays, 'days').utc().format();
        let endOfflineHotel = moment(end).add(this.state.hotelOffEndFloatDays, 'days').utc().format();
        hotelItinerary.map(hotel => {
          if (hotel.fromDate && !this.judgeSubset(startOfflineHotel, endOfflineHotel, hotel.fromDate)) {
            isOfflineHotelOK = false;
          }
          if (hotel.leaveDate && !this.judgeSubset(startOfflineHotel, endOfflineHotel, hotel.leaveDate)) {
            isOfflineHotelOK = false;
          }
        });
        if (!isOfflineHotelOK) {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  };

  //校验日期date是否在start，end之间，包含两侧日期，精度到秒
  judgeSubset = (start, end, date) => {
    return moment(date).isSame(start) || moment(date).isSame(end) || moment(date).isBetween(start, end, 'second');
  };

  //连选日期变更后刷新date数据
  refreshRangeDate = (values, startDate, endDate) => {
    values.map(res => {
      if (res.messageKey === 'start_date') {
        res.value = startDate;
      }
      if (res.messageKey === 'end_date') {
        res.value = endDate;
      }
    });
  };

  componentDidMount() {

    this.getFormInfo();
    this.isCounterSignEnable();

    let sub = this.state.subsidyCtrl;
    //是否进行预算校验
    sub.isBudgetCheck = this.props.profile['travel.budget.check'];
    //是否必须添加行程
    sub.itineraryRequire = this.props.profile['ta.itinerary.required'] ? this.props.profile['ta.itinerary.required'] : false;
    //检查是否是hr人员并获取值
    const { params } = this.props;
    let userOID = this.props.user.userOID;
    if (params.applicantOID && params.applicantOID !== ':applicantOID') {
      userOID = params.applicantOID;
    }
    requestService.getUserIsHr(userOID).then(res => {
      console.log("res", res)
      if(res.data){
        this.setState({
          userIsHr: res.data.isHr,
          hrInfo: res.data
        })
      }
    })
    this.setState({ subsidyCtrl: sub });
  };

  componentWillUnmount() {
    console.log('----componentWillUnmount-----')
    this.setState({ participantChanged: false });
  };

  //检查差旅申请单配置的差补规则中影响差补的表单项
  checkedIsSetSubsidyRule = (res) => {
    let maps = res.data.customFormPropertyMap;
    if (!maps) {
      return;
    }
    let subsidyDimension = maps['travel.subsidies.dimension'] ? JSON.parse(maps['travel.subsidies.dimension']) : false;
    if (subsidyDimension) {
      if (subsidyDimension.formFieldOIDs && subsidyDimension.formFieldOIDs.length > 0) {
        this.setState({
          isHaveSubsidyRules: true,
          subsidyRulesFieldOID: subsidyDimension.formFieldOIDs
        })
      }
    }
  }

  //控制差旅日期范围，是否是强管控
  processRangeDateEnable = (data) => {
    let maps = data.customFormPropertyMap;
    if (!maps) {
      return;
    }
    if (maps['application.control.daterange.enable'] === 'true') {
      this.setState({
        isControlRangeDate: true
      });
    }
    if (maps['application.property.control.fields.hotel']) {
      let hotelCtrl = JSON.parse(maps['application.property.control.fields.hotel']);
      if (hotelCtrl.fromDate && hotelCtrl.fromDate.floatDays) {
        this.setState({
          hotelStartFloatDays: hotelCtrl.fromDate.floatDays
        });
      }
      if (hotelCtrl.leaveDate && hotelCtrl.leaveDate.floatDays) {
        this.setState({
          hotelEndFloatDays: hotelCtrl.leaveDate.floatDays
        });
      }
    }
    if (maps['application.property.control.fields.offline.hotel']) {
      let hotelOffCtrl = JSON.parse(maps['application.property.control.fields.offline.hotel']);
      if (hotelOffCtrl.fromDate && hotelOffCtrl.fromDate.floatDays) {
        this.setState({
          hotelOffStartFloatDays: hotelOffCtrl.fromDate.floatDays
        });
      }
      if (hotelOffCtrl.leaveDate && hotelOffCtrl.leaveDate.floatDays) {
        this.setState({
          hotelOffEndFloatDays: hotelOffCtrl.leaveDate.floatDays
        });
      }
    }
  };

  /**
   * 监听差补规则中配置的影响差补的表单项
   * @param cust 表单项数组
   * @param isEditing 是否是编辑状态
     */
  subsidyRulesListener = (cust, isEditing) => {
    if (this.state.isHaveSubsidyRules) {
      cust.map((item, index) => {
        this.state.subsidyRulesFieldOID.map(oid => {
          if (item.fieldOID === oid) {
            let baseStartData = this.state.copyDefaultValues[index];
            if (isEditing && baseStartData && baseStartData.value !== item.value && this.canGo && this.state.total > 0) {
              if (this.state.isHaveRoute && this.state.total > 0) {
                this.canGo = false;
                let currentKey = item.formValueOID;
                this.baseModalShow(messages('request.key453', { arg1: item.fieldName }/*更改{arg1}将清空已添加差补*/), '', baseStartData, currentKey, index, item, true);
              } else {
                this.updateCopyDefaultValue(index, item);
              }
            }
          }
        })
      })
    }
  }

  componentWillReceiveProps() {
    let isEditing = !!this.props.params.applicationOID;
    let values = this.props.form.getFieldsValue();
    let cust = [];
    let custFormValues = isEditing ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    if (this.state.editTicketInfoVisible) {
      if (this.state.formType === 2001) {
        if (values.travelBudgetDetail) {
          let amount = values.travelBudgetDetail.amount ? values.travelBudgetDetail.amount : 0;
          this.setState({
            travelBudgetDetailObj: JSON.parse(JSON.stringify(values.travelBudgetDetail)),
            amount: amount,
            totalBudget: this.state.total + amount
          });
        } else {
          this.setState({
            travelBudgetDetailObj: null,
            amount: 0,
            totalBudget: this.state.total
          });
        }
      }
      return;
    }
    if (this.state.formType === 2001) {
      if (custFormValues) {
        cust = this.getCustFormValues(values);
      }
      let amount = 0;
      this.subsidyRulesListener(cust, isEditing);
      cust.map((item, index) => {
        if (item.messageKey === "budget_detail") {
          amount = item.value ? JSON.parse(item.value).amount : 0;
          this.setState({
            amount: amount,
            totalBudget: this.state.total + amount
          });
        }
        if (item.messageKey === 'start_date') {
          let endDateValue = travelUtil.getFormHeadValue(cust, 'end_date');
          item.endDate = endDateValue;
          let baseStartData = this.state.copyDefaultValues[index];
          if (isEditing && baseStartData && baseStartData.value !== item.value && this.canGo) {
            if (this.state.isHaveRoute) {
              this.canGo = false;
              let currentKey = item.formValueOID;
              let isHaveSubsidy = this.state.total > 0 ? true : false;
              // let mesStr = messages('request.key452',{arg1:item.fieldName}/*更改{arg1}可能导致行程与出差日期不匹配*/);
              let mesStr = '';
              let mesSubsidy = isHaveSubsidy ? messages('request.key453', { arg1: item.fieldName }/*更改{arg1}将清空已添加差补*/) : '';
              mesSubsidy && this.baseModalShow(mesSubsidy, mesStr, baseStartData, currentKey, index, item);
            } else {
              this.updateCopyDefaultValue(index, item);
            }
          }
        }
        if (item.messageKey === 'end_date') {
          let startDateValue = travelUtil.getFormHeadValue(cust, 'start_date');
          item.startDate = startDateValue;
          let baseStartData = this.state.copyDefaultValues[index];
          if (isEditing && baseStartData && baseStartData.value !== item.value && this.canGo) {
            if (this.state.isHaveRoute) {
              this.canGo = false;
              let currentKey = item.formValueOID;
              let isHaveSubsidy = this.state.total > 0 ? true : false;
              // let mesStr = messages('request.key452',{arg1:item.fieldName}/*更改{arg1}可能导致行程与出差日期不匹配*/);
              let mesStr = '';
              let mesSubsidy = isHaveSubsidy ? messages('request.key453', { arg1: item.fieldName }/*更改{arg1}将清空已添加差补*/) : '';
              mesSubsidy && this.baseModalShow(mesSubsidy, mesStr, baseStartData, currentKey, index, item);
            } else {
              this.updateCopyDefaultValue(index, item);
            }
          }
        } else if (item.messageKey === 'select_participant') {//参与人员
          let baseStartData = this.state.copyDefaultValues[index];
          if (isEditing && baseStartData && travelUtil.checkIsArrayChange(baseStartData.value, item.value || item.showValue, 'userOID', true) && this.canGo) {
            if (this.isReplace) {
              this.updateCopyDefaultValue(index, item, true);
            } else {
              if (this.state.isHaveRoute && this.state.total > 0) {
                this.canGo = false;
                let currentKey = item.formValueOID;
                this.baseModalShow(messages('request.key171'/*更改参与人员将清空已添加差补*/), '', baseStartData, currentKey, index, item);
              } else {
                this.updateCopyDefaultValue(index, item);
              }
            }
          }
        } else if (item.messageKey === 'applicant') {//申请人 改动
          let baseStartData = this.state.copyDefaultValues[index];
          if (baseStartData && baseStartData.value !== item.value && this.canGo) {
            this.canGo = false;
            let isInParticipant = false;//原申请人是否在参与人中
            let participant = travelUtil.getFormHeadValue(cust, 'select_participant');//获取参与人数据
            if (participant) {
              participant.map(p => {//遍历参与人看原申请人是否在其中
                if (baseStartData.value === p.userOID) {
                  isInParticipant = true;
                }
              })
            }
            if (isInParticipant) {//原申请人在参与人员中-->弹框提示
              let currentKey = isEditing ? item.formValueOID : item.fieldOID;
              let tipMessage = isEditing && this.state.total > 0 ? messages('request.key171'/*更改参与人员将清空已添加差补*/) : '';
              this.baseModalShow(messages('request.key172'/*新的申请人将替换原参与人员中的默认数据*/), tipMessage, baseStartData, currentKey, index, item);
            } else {//原申请人不在参与人员，中直接修改申请人
              this.updateCopyDefaultValue(index, item);
              this.soveApplicant(item, { value: baseStartData.value }, false);//根据申请人修改对应默认值
            }
          }
        }
      });
    } else {
      if (custFormValues) {
        //getCustFormValues在不传isClear的情况下相当于刷新了下this.state.info.custFormValues或者this.state.formInfo.customFormFields的值
        cust = this.getCustFormValues(values);
      }
    }
  };

  //修改申请人
  handleApplicantChange = (field, applicantOID) => {
    this.setState({ loading: true });
    baseService.changeLoginInfo(applicantOID).then(() => {
      requestService.getFormValue(this.props.user.userOID, this.props.params.formOID).then(res => {
        this.setState({
          loading: false,
          formDefaultValue: res.data
        }, () => {
          this.props.form.resetFields()
        })
      })
    }).catch(() => {
      location.href = '/';
      message.error(messages('request.key169'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/)); //呼，服务器出了点问题，请联系管理员或稍后再试:(
    })
  };

  //差旅申请单申请人更改
  soveApplicant = (newField, data, isReplace) => {
    travelService.getPrincipalsInfo(newField.value).then(res => {
      if (this.state.currentCodeType !== res.data.currencyCode) {
        this.setState({ currentCodeType: res.data.currencyCode });
        this.noChangePar = true;
      } else {
        this.noChangePar = false;
      }
    });
    let status = this.props.params.applicationOID ? 'edit' : 'create';
    let custFormValues = status === 'edit' ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let formOID = status === 'edit' ? this.props.params.formOID : this.state.formInfo.formOID;
    travelUtil.setDefaultFormUtil(status, custFormValues, newField, formOID, data, this.executeCall, isReplace);
  };

  //更新复制默认值
  updateCopyDefaultValue = (index, newField, replace) => {
    this.setState({ formIsChange: true });
    let copy = this.state.copyDefaultValues;
    copy.map(res => {
      if (res.messageKey === newField.messageKey) {
        res.value = newField.value;
      }
    });
    this.setState({ copyDefaultValues: copy, formIsChange: true }, () => {
      this.canGo = true;
      replace && (this.isReplace = false);
    });
  }

  baseModalShow = (mes, sage, data, currentKey, index, newField, isSubsidyRule) => {
    const { messageKey } = data;
    console.log('changed messageKey', messageKey)
    const methodName = messageKey === 'select_participant' ? 'warning' : 'confirm';
    Modal[methodName]({
      title: messages('request.key173'/*提示*/),
      content: <div>
        <p>{mes}</p>
        <p>{sage}</p>
      </div>,
      okText: messages('request.key174'/*更改*/),
      cancelText: messageKey === 'select_participant' ? undefined : messages('request.key175'/*取消*/),
      onOk: () => {
        if (messageKey === 'applicant') {//更改的是申请人    参与人要替换掉；成本中心，公司，部门都改默认值
          // 单独处理
          this.isReplace = true;
          //参数中使用{value：data.value},而不是直接使用 data，是因为data是数组copyDefaultValue的一个项，当该项
          //被更新后，传入的值也就改变了，即会出现传入时是a,某一时刻就变成copyDefaultValue更新后的值b了
          this.soveApplicant(newField, { value: data.value }, true);
        }
        if (this.state.total > 0)
          this.clearSubsidy();
        //更新副本中的默认值
        this.updateCopyDefaultValue(index, newField);
      },
      onCancel: () => {
        let setData = {};
        let defaultValues = this.state.defaultValues;
        let formInfo = this.state.formInfo;
        if (isSubsidyRule) {
          setData[currentKey] = customField.getDefaultValue(data, data.initValue, formInfo.formCode);
        } else {
          setData[currentKey] = travelUtil.changeValueUtil(data);
        }
        if (!!this.props.params.applicationOID) {
          defaultValues[index].value = this.state.copyDefaultValues[index].value;
        }
        formInfo['customFormFields'][index].value = this.state.copyDefaultValues[index].value;
        this.props.form.setFieldsValue(setData);
        this.setState({
          defaultValues: defaultValues,
          formInfo: formInfo
        }, () => {
          this.canGo = true;
        });
      },
    });
  };

  //日期校验范围不通过，不允许修改日期
  baseModalDisableDateChange = (currentKey) => {
    Modal.error({
      title: messages('request.key176'/*控制出差日期范围*/),
      content: messages('request.key177'/*出差往返日期必须包含已保存的行程日期范围，请检查后再修改*/),
      okText: messages('common.ok')/*'确定'*/,
      onOk: () => {
        this.cancelDateChange(currentKey);
      }
    });
  };

  //取消日期更改
  cancelDateChange = (currentKey) => {
    let copy = this.state.copyDefaultValues;
    let oldStartDate = null;
    let oldEndDate = null;
    let setData = {};
    copy.map(item => {
      if (item.messageKey === 'start_date') {
        oldStartDate = item.value;
      }
      if (item.messageKey === 'end_date') {
        oldEndDate = item.value;
      }
    });
    if (this.isSetCloseEnabled) {
      this.closeDate = moment(oldEndDate).add(this.closeDay, 'days');
    }
    let defaultValues = this.state.defaultValues;
    let formInfo = this.state.info;
    this.refreshRangeDate(formInfo.custFormValues, oldStartDate, oldEndDate);
    formInfo.custFormValues.map((custFormValue, index) => {
      if (custFormValue.messageKey === 'range_picker') {
        custFormValue.showValue = [moment(oldStartDate), moment(oldEndDate)];
        defaultValues[index].showValue = [moment(oldStartDate), moment(oldEndDate)];
        setData[currentKey] = [moment(oldStartDate), moment(oldEndDate)];
      }
    });
    this.props.form.setFieldsValue(setData);
    this.setState({
      defaultValues: defaultValues,
      info: formInfo
    }, () => {
      this.canGo = true;
    });
  };

  baseModalShowForRangeDateChange = (mes, sage, currentKey, startDate, endDate) => {
    Modal.info({
      title: messages('request.key173'/*提示*/),
      content: <div>
        <p>{mes}</p>
        <p>{sage}</p>
      </div>,
      okText: messages('common.ok'/*确认*/),
      // cancelText: messages('request.key175'/*取消*/),
      onOk: () => {
        this.processDateChange(startDate, endDate);
      },
      // onCancel: ()=> {
      //   this.cancelDateChange(currentKey);
      // },
    });
  };

  //执行日期更改
  processDateChange = (startDate, endDate) => {
    if (this.state.total > 0)
      this.clearSubsidy();
    let copy = this.state.copyDefaultValues;
    this.refreshRangeDate(copy, startDate, endDate);
    this.getDays(startDate, endDate);
    this.setState({
      formIsChange: true,
      copyDefaultValues: copy
    }, () => {
      this.canGo = true;
    });
  };

  //处理差旅申请单，费用申请单的日期连选
  //type 新建create 编辑edit
  processTravelDate = (applicationData, type) => {
    if (applicationData.formType === 2001 || applicationData.formType === 2002) {
      let rangePicker = {
        messageKey: 'range_picker',
        fieldOID: travelUtil.generateUid(),
        fieldName: applicationData.formType === 2001 ? messages('request.key170'/*出差往返日期*/) : messages('request.key674')/*开始结束日期*/,
        fieldType: 'TEXT',
        enableTime: false,
        defaultValueTime: [], //启用时间的默认值
        required: true,
        sequence: null,
        value: null
      }
      let hasStartEndDate = 0;
      let startDate = null;
      let endDate = null;
      let enableStartDateTime = false; //开始日期启用时间
      let enableEndDateTime = false; //结束日期启用时间
      if (type === 'create') {
        applicationData.customFormFields.map((field) => {
          if (field.messageKey === 'start_date') {
            rangePicker.sequence = field.sequence;
            enableStartDateTime = this.processEnableTime(field);
            rangePicker.defaultValueTime.push(this.processDefaultTime(field));
            hasStartEndDate++;
          }
          if (field.messageKey === 'end_date') {
            enableEndDateTime = this.processEnableTime(field);
            rangePicker.defaultValueTime.push(this.processDefaultTime(field));
            hasStartEndDate++;
          }
        });
        if (hasStartEndDate === 2) {
          if (enableStartDateTime && enableEndDateTime) {
            rangePicker.enableTime = true;
          }
          applicationData.customFormFields.push(rangePicker);
          this.setState({ isShowRangePicker: true }, () => {
            this.processDisableTime(applicationData, type);
          });
        }
      }
      if (type === 'edit') {
        applicationData.custFormValues.map((field) => {
          if (field.messageKey === 'start_date') {
            rangePicker.sequence = field.sequence;
            startDate = field.value;
            enableStartDateTime = this.processEnableTime(field);
            hasStartEndDate++;
          }
          if (field.messageKey === 'end_date') {
            endDate = field.value;
            enableEndDateTime = this.processEnableTime(field);
            hasStartEndDate++;
          }
        });
        if (hasStartEndDate === 2) {
          if (enableStartDateTime && enableEndDateTime) {
            rangePicker.enableTime = true;
          }
          rangePicker.formValueOID = 'virtual_range_picker';
          rangePicker.showValue = [moment(startDate), moment(endDate)];
          applicationData.custFormValues.push(rangePicker);
          this.setState({ isShowRangePicker: true }, () => {
            this.processDisableTime(applicationData, type);
          });
        }
      }
    }
  };

  //处理是否停用日期
  //type 新建create 编辑edit
  processDisableTime = (applicationData, type) => {
    //新建时的处理
    if (applicationData.customFormProperties.enabled === 1 && type === 'create') {  //是否和停用启用有关
      this.isSetCloseEnabled = true;
      this.closeDay = applicationData.customFormProperties.closeDay;
      let date = new Date();
      this.closeDate = moment(date).add(this.closeDay, 'days');
    }
    //编辑时的处理
    if (applicationData.closeEnabled && type === 'edit') {
      this.isSetCloseEnabled = true;
      this.closeDay = applicationData.customFormProperties.closeDay;
      if (applicationData.closeDate) {
        this.closeDate = moment(applicationData.closeDate);
      }
    }
  };

  //处理是否启用时间
  processEnableTime = (field) => {
    let enableTime = false;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint) && JSON.parse(field.fieldConstraint).enableTime) {
      enableTime = true;
    }
    return enableTime;
  };
  //处理启用时间默认值
  processDefaultTime = (field) => {
    let defaultTime = null;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint)) {
      if (JSON.parse(field.fieldConstraint).defaultTime) {
        defaultTime = moment(moment(JSON.parse(field.fieldConstraint).defaultTime).format('HH:mm'), 'HH:mm');
      } else {
        if (field.messageKey === 'start_date') {
          defaultTime = moment('00:00', 'HH:mm');
        }
        if (field.messageKey === 'end_date') {
          defaultTime = moment('23:59', 'HH:mm');
        }
      }
    }
    return defaultTime;
  };

  //详情页设置申请人控件不可更改
  setApplicantDisable = (fields) => {
    fields.map(item => {
      if (item.messageKey === 'applicant') {
        item.isReadOnly = true;
      }
    });
  };

  updateOwnerInfo =() => {
    let fields = this.state.formDefaultValue;
    const { user, params } = this.props;
    //查找相关人员的信息
    let owner =null;
    if (this.props.form.getFieldsValue().cardOwner) {
      owner = this.props.form.getFieldsValue().cardOwner;
    }
    this.setState({
      loading: true,
    })
    this.props.form.resetFields()
    //更新数据
    if(owner.length > 0){
      requestService.getCardOwerEidValue(owner[0].eid).then(res => {
        let data = res.data
        if(data!=""){
          Promise.all([
            requestService.getDept(owner[0].name),
            requestService.getQuotaValue(data)
        ]).then(res => {
            //查找部门
            if(res[0].data && res[0].data.length>1){
              res[0].data.map(temp=>{
                if(temp.userOID === data){
                  fields[0].value = temp.departmentOID
                  fields[0].name = temp.departmentName
                }
              })
            }else if(res[0].data && res[0].data.length ===1){
              fields[0].value = res[0].data[0].departmentOID
            }else {
              message.error(messages('request.key186'/*部门为空.*/));
            }
            fields.map(item=> {
              if(item.fieldCode === 'card. owner'){
                item.value = owner[0].name
              }
            })
            //部门需要单独查询
            fields[1].value = res[1].data.user.company.companyOID //companyOID
            fields[3].value = owner[0].eid //eid
            fields[4].value = owner[0].cardNumber //cardNumber 完整卡号
            this.setState({
              loading: false,
              formDefaultValue: fields
            })
          })
        }
      })
    }
  }

  //获取表单配置
  getFormInfo = () => {
    const { params, company } = this.props;
    this.setState({ loading: true });
    let giftDeclareValue = null;
    let isSwitchOn = null;
    if (this.props.params.applicationOID) {
      Promise.all([
        requestService.getRequestDetail(this.props.params.applicationOID)
      ])
      .then(res1 => {
        /**
         * 如果是礼品申报单多加载一个礼品申报单多详情，
         * 加载完之后`return res1`, 不影响原来多逻辑
         */
        if (res1[0].data.formCode === 'SQ008') {
          // console.log(res1[0].data)
          return giftDeclareService.getGiftDeclare({ businessCode: res1[0].data.businessCode }).then(resOfGift => {
            giftDeclareValue = resOfGift.data
            // console.log('giftDeclareValue', giftDeclareValue)
            if (!giftDeclareValue) {
              errorMessage(resOfGift)
              return res1
            }
            if (Array.isArray(giftDeclareValue)) {
              giftDeclareValue = giftDeclareValue[0]
            }
            if (!giftDeclareValue) {
              giftDeclareValue = {}
            }
            return res1
          })
        } else {
          return res1
        }
      })
        .then(res1 => {
        res1[0].data.custFormValues.map(item => {
          if (item.isSwitchOn != null) {
            isSwitchOn = item.isSwitchOn;
          }
        })
        requestService.getCustomForm(this.props.params.formOID).then(res => {
          this.customFormFieldsOrigin = JSON.parse(JSON.stringify(res.data));
          this.setApplicantDisable(res.data.customFormFields);
          this.processTravelDate(res.data, 'create');
          res.data.customFormFields.sort((a, b) => a.sequence > b.sequence || -1);//wjk add 180523
          !params.applicationOID && this.copyDefaultCust(res, 'create');
          this.checkedIsSetSubsidyRule(res);//wjk add 18 06 01
          this.processRangeDateEnable(res.data);//处理控制出差日期范围
          this.setState({
            loading: !!params.applicationOID,
            formInfo: res.data,
            originalFormInfo: deepFullCopy(res.data),
            formType: res.data.formType,
            currentCodeType: company.baseCurrency,
            manageType: res.data.customFormProperties.manageType,
            editTicketInfoVisible: res.data.formType === 2001 && params.applicationOID,
            showSubmitBtn: res.data.formCode !== 'SQ024'
          }, () => {
            const { formInfo, formType } = this.state;
            if (formInfo.formCode === 'SQ019') {
              this.getThirdType();
            }
            if (this.state.jobId) {
              this.getJobInfo();
            }
            if (params.applicationOID) {
              this.getInfo(formType)
            } else {
              this.getFormDefaultValue();
            }
            if (formInfo.formCode === 'SQ008') {
              setGiftDeclareValue(giftDeclareValue, this)
            }
          })
        })
      })

    } else {
      requestService.getCustomForm(this.props.params.formOID).then(res => {
        this.customFormFieldsOrigin = JSON.parse(JSON.stringify(res.data));
        this.setApplicantDisable(res.data.customFormFields);
        this.processTravelDate(res.data, 'create');
        res.data.customFormFields.sort((a, b) => a.sequence > b.sequence || -1);//wjk add 180523
        !params.applicationOID && this.copyDefaultCust(res, 'create');
        this.checkedIsSetSubsidyRule(res);//wjk add 18 06 01
        this.processRangeDateEnable(res.data);//处理控制出差日期范围
        this.setState({
          formDate:res.data.customFormFields,
          loading: !!params.applicationOID,
          formInfo: res.data,
          originalFormInfo: deepFullCopy(res.data),
          formType: res.data.formType,
          currentCodeType: company.baseCurrency,
          manageType: res.data.customFormProperties.manageType,
          editTicketInfoVisible: res.data.formType === 2001 && params.applicationOID,
          showSubmitBtn: res.data.formCode !== 'SQ024'
        }, () => {
          const { formType, formInfo } = this.state;
          if (formInfo.formCode === 'SQ019') {
            this.getThirdType();
          }
          if (this.state.jobId) {
            this.getJobInfo();
          }
          if (params.applicationOID) {
            this.getInfo(formType)
          } else {
            this.getFormDefaultValue();
          }
        })
      })
    }
  };

  //获取表单默认值
  getFormDefaultValue = () => {
    const { jobId, formInfo } = this.state;
    const { user, params } = this.props;
    const { formCode } = formInfo;
    let defaultValue =[];
    let userOID = user.userOID;
    let userEID = null;
    let cardNumber = null;

    if (params.applicantOID && params.applicantOID !== ':applicantOID') {
      userOID = params.applicantOID;
    }
    requestService.getUserIsHr(userOID).then(res => {
      if(res.data){
        userEID = res.data.eid;
        cardNumber = res.data.cardNumber;
      }
    })
    requestService.getFormValue(userOID, params.formOID, jobId).then(res => {
      if (!['SQ005', 'SQ006', 'SQ007'].includes(formCode)) {
        let data = res.data;
        // 移除默认值
        // if(formCode === 'SQ002'){
        //   let custForm = formInfo.customFormFields || [];
        //   custForm.map(i =>{
        //     if(i.fieldCode == 'kq'){
        //       data.push({
        //         fieldOID: i.fieldOID,
        //         fieldName: i.fieldName,
        //         name: "实体卡券",
        //         value: "001",
        //         showValue: null,
        //         code: "001",
        //         attachmentImages: null
        //       })
        //     }
        //   })
        // }
        this.setState({
          loading: false,
          formDefaultValue: res.data
        })
      } else {
        defaultValue = res.data
        if(formCode =='SQ005'){
          requestService.getQuotaValue(userOID).then(res => {
            let temp_quota = {fieldOID:this.state.formDate[2].fieldOID,value:res.data.quota,visableType:1}
            let temp_mobile = {fieldOID:this.state.formDate[3].fieldOID,value:res.data.user.contact.mobile,required:true}
            let temp_email = {fieldOID:this.state.formDate[4].fieldOID,value:res.data.user.contact.email,visableType:1}
            defaultValue.push(temp_quota)
            defaultValue.push(temp_mobile)
            defaultValue.push(temp_email)
            this.setState({
              loading: false,
              formDefaultValue: defaultValue
            })
          })
        }
        if(formCode =='SQ006'){
          requestService.getQuotaValue(userOID).then(res => {
            let temp_nowQuota = {fieldOID:this.state.formDate[6].fieldOID,value:res.data.nowQuota}
            let temp_quota = {fieldOID:this.state.formDate[7].fieldOID,value:res.data.quota}
            defaultValue.push(temp_nowQuota)
            defaultValue.push(temp_quota)
            this.setState({
              loading: false,
              formDefaultValue: defaultValue
            })
          })
        }
        if(formCode =='SQ007'){
          requestService.getQuotaValue(userOID).then(res => {
            let temp_name = {fieldOID:this.state.formDate[0].fieldOID,value:res.data.user.contact.fullName,fieldCode:this.state.formDate[0].fieldCode}
            let temp_eid = {fieldOID:this.state.formDate[3].fieldOID,value:userEID,required:true}
            let temp_cardNumber = {fieldOID:this.state.formDate[4].fieldOID,value:cardNumber,required:true}
            // defaultValue.push(temp_name)
            let applicantOID = this.props.params.applicantOID && this.props.params.applicantOID.indexOf('applicantOID') == 1 ? true : false;
            let dataList = applicantOID ? this.state.formDate : this.state.copyDefaultValues;
            console.log("dataList", dataList)
            dataList.map(item => {
              dataList.map(item =>{
                let obj = {};
                if(item.fieldName === '公务卡归属人EID'){
                  if (applicantOID) {
                    obj[item.fieldOID] = userEID
                  } else {
                    obj[item.formValueOID] = userEID
                  }
                  this.props.form.setFieldsValue(obj)
                }
                // if(item.fieldName === '公务卡归属人'){
                //   if (applicantOID) {
                //     obj[item.fieldOID] = userOID
                //   } else {
                //     obj[item.formValueOID] =  userOID
                //   }
                //   this.props.form.setFieldsValue(obj)
                // }
                // if(item.fieldName === '公务卡完整卡号'){
                //   if (applicantOID) {
                //     obj[item.fieldOID] = cardNumber
                //   } else {
                //     obj[item.formValueOID] = cardNumber
                //   }
                //   this.props.form.setFieldsValue(obj)
                // }
              })
            })
            defaultValue.push(temp_eid)
            defaultValue.push(temp_cardNumber)
            console.log('defaultValue', this.props.form.getFieldsValue())
            this.setState({
              loading: false,
              formDefaultValue: defaultValue
            })
          })
        }
      }
    })

  };

  executeCall = (currentUpdate, budgetDetailKey) => {
    currentUpdate.map(item => {
      this.props.form.setFieldsValue(item);
    });
    if (budgetDetailKey && this.noChangePar) {
      this.props.form.setFieldsValue({ [budgetDetailKey]: null });
    }
  };

  //获取申请单详情
  getInfo = () => {
    //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
    const { applicationOID } = this.props.params;
    requestService.getRequestDetail(applicationOID).then(res => {
      let valuesOnlyForShow = JSON.parse(JSON.stringify(res.data.custFormValues));
      let warningList = res.data.warningList ? JSON.parse(res.data.warningList) : [];
      let isHasTravelBudgetDetail = false;
      let travelBudgetDetailObj = null;
      valuesOnlyForShow.map((valueItem, index) => {
        if (valueItem.messageKey === 'budget_detail') {
          isHasTravelBudgetDetail = true;
          travelBudgetDetailObj = valueItem.value ? JSON.parse(valueItem.value) : null;
          if (travelBudgetDetailObj && travelBudgetDetailObj.budgetDetail && travelBudgetDetailObj.budgetDetail.length) {
            travelBudgetDetailObj.refreshAmount = true;//标记重算金额，同时会把开了分摊但是没有默认分摊的费用加上默认分摊
          }
        }
      });
      //代提逻辑
      if (this.props.loginUser.userOID !== res.data.applicantOID) {
        this.setState({ isProxy: true });
        baseService.changeLoginInfo(res.data.applicantOID);
      }
      this.setApplicantDisable(res.data.custFormValues);
      this.processTravelDate(res.data, 'edit');
      //wjk add 排序只需拿到数据之后排一次，render函数中排序，会排序多次，同等优先级项排序结果会不同
      res.data.custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
      let isCustListSwitch = false;
      let principalOID = undefined;
      let thirdUserEid = undefined;
      if (['SQ017', 'SQ018'].includes(res.data.formCode)) {
        res.data.custFormValues.map(item => {
          if (item.messageKey === 'switch') {
            isCustListSwitch = (item.value === 'true') ? true : false
          }
          if (item.messageKey === 'select_user') {
            principalOID = item.value ? item.value : undefined
          }
        })
      }
      if (['SQ019'].includes(res.data.formCode)) {
        res.data.custFormValues.map(item => {
          if (item.fieldCode === 'carIID2') {
            thirdUserEid = item.valueCode ? item.valueCode : undefined
          }
        })
      }
      // console.log('thirdUserEid', thirdUserEid)
      this.setState({
        loading: false,
        jobId: res.data.jobId,
        info: res.data,
        warningList,
        approvalHistory: res.data.approvalHistorys || [],
        defaultValues: this.mixinDefaultValues(res.data.custFormValues),
        valuesOnlyForShow,
        travelBudgetDetailObj,
        isHasTravelBudgetDetail,
        currentCodeType: res.data.currencyCode ? res.data.currencyCode : this.props.company.baseCurrency,
        referenceApplicationOID: res.data.referenceApplicationOID,
        travelItinerarys: res.data.travelApplication && (res.data.travelApplication.travelItinerarys || []),
        travelElementServiceName: res.data.travelApplication && (res.data.travelApplication.supplierServiceName || ''),
        isCustListSwitch,
        principalOID,
        thirdUserEid
      }, () => {
        this.getJobInfo();
        this.getThirdPartyInfo();
        this.getBudgetExplainNumber();
      });
      this.copyDefaultCust(res, 'edit');//wjk add 备份默认值
    })
  };

  mixinDefaultValues = (rawValues) => {
    const { customFormFields = [] } = this.state.originalFormInfo;
    return rawValues.map(rawValue => {
      const field = customFormFields.find(item => item.fieldOID === rawValue.fieldOID) || {}
      return {
        ...field,
        ...rawValue
      }
    })
  }

  //详情页（显示编辑按钮的页面），删除非法参与人后，重新刷新【申请单详情】信息
  refreshInfoAfterDelPartis = (info) => {
    const valuesOnlyForShow = JSON.parse(JSON.stringify(info.custFormValues));
    this.setState({
      info,
      defaultValues: info.custFormValues,
      valuesOnlyForShow
    });
    this.copyDefaultCust(res, 'edit');//wjk add 备份默认值
  };

  hideLoading = () => {
    this.setState({ saveLoading: false, loading: false, submitLoading: false });
  };

  //获取岗位信息
  getJobInfo = () => {
    const { jobId, formInfo, formDate } = this.state;
    baseService.getJobInfo(jobId).then(res => {
      let list = formInfo.customFormFields || formDate;
      list.map(item => {
        if (item.fieldCode === 'ApplicantRank') {
          let obj = {};
          obj[item.fieldOID] = res.data.rank;
          item.value = res.data.rank;
          // 为了解决页面频繁出现无法默认带出申请人职级这个问题，增加一个50ms的延时
          const timeId = setTimeout(() => {
            this.props.form.setFieldsValue(obj);
            window.clearTimeout(timeId)
          }, 50)
        }
      })
      this.setState({ jobInfo: res.data, formInfo });
    });
  };

  //获取第三方返回信息
  getThirdPartyInfo = () => {
    const { info } = this.state;
    const { profile } = this.props;
    if (profile['request.external.info.display']) {
      requestService.getThirdPartyInfo(info.applicationOID).then(res => {
        this.setState({ thirdPartyInfo: res.data });
      });
    }
  };

  //获取预算执行结果数量
  getBudgetExplainNumber = () => {
    const { info } = this.state;
    let params = {
      applicationOID: info.applicationOID
    };
    requestService.getBudgetExplain(params).then(res => {
      this.setState({
        budgetExplainNumber: Number(res.data || 0)
      })
    });
  };

  //判断是否可以加签
  isCounterSignEnable = () => {
    let params = {
      companyOID: this.props.company.companyOID,
      formOID: this.props.params.formOID,
      counterSignType: 'enableAddSignForSubmitter',
    };
    approveRequestService.postAddSignEnableScope(params).then(res => {
      // this.setState({ signEnable: res.data });
      if (res.data.enabled) {
        //加签人范围
        this.setState(
          {
            signEnable: res.data.enabled,
            signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs
          }, () => {
          });

      }

    })
  };

  /**
   * 备份默认值，做修改参照基准
   * @param res
   * @param status 表单状态 edit create
     */
  copyDefaultCust = (res, status) => {
    let dev = [];
    dev.checkedChange = this.checkedChange;//设置监听
    dev.checkedOk = this.checkedOk;//设置监听
    dev.expectStopDate = this.expectStopDate;//设置监听
    dev.applicationData = res.data;//差旅、费用申请单需要根据配置设置预计停用日期
    //添加更改状态单子不可编辑 申请人，参与人，外部参与人数量
    if (res.data.sourceApplicationOID) {
      res.data.custFormValues = travelUtil.setDisabledValues(res.data.custFormValues);
    }
    if (!this.props.params.applicationOID && status === 'create') {
      res.data.customFormFields.map(m => {
        dev.push({
          value: m.messageKey === 'currency_code' ? this.props.company.baseCurrency : m.value,//新建单据时copyValue中币种要塞个默认值
          messageKey: m.messageKey,
          fieldOID: m.fieldOID,
          fieldName: m.fieldName,
          required: m.required,
          formType: this.state.formType,
          showName: { name: m.showValue },
          dataSource: m.dataSource,
          fieldContent: m.fieldContent,
          fieldConstraint: m.fieldConstraint,
          fieldCode: m.fieldCode,
        });
      });
      this.setState({ copyDefaultValues: dev });
    } else if (status === 'edit') {
      res.data.custFormValues.map(m => {
        dev.push({
          value: m.value,
          messageKey: m.messageKey,
          formValueOID: m.formValueOID,
          fieldOID: m.fieldOID,
          fieldName: m.fieldName,
          required: m.required,
          formType: this.state.formType,
          showName: { name: m.showValue },
          initValue: { value: m.value, name: m.showValue },
          showValue: m.showValue,
          dataSource: m.dataSource,
          fieldContent: m.fieldContent,
          fieldConstraint: m.fieldConstraint,
          fieldCode: m.fieldCode,
        });
      });
      this.setState({ copyDefaultValues: dev });
    }
  };

  //获取保存、提交申请单时的custFormValues
  //isClearRange是否要去除连选控件
  getCustFormValues = (values, isClearRange) => {
    //let custFormValues = this.props.params.applicationOID ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let custFormValues = null;
    if (isClearRange) {
      if (this.state.editTicketInfoVisible) {
        custFormValues = JSON.parse(JSON.stringify(this.state.valuesOnlyForShow));
        return custFormValues;
      } else {
        //提交／保存前是不需要对象引用的，深拷贝一份做为传给后台的数据，如果接口出错了，也不影响原有的数据
        custFormValues = this.props.params.applicationOID ? JSON.parse(JSON.stringify(this.state.info.custFormValues)) : JSON.parse(JSON.stringify(this.state.formInfo.customFormFields));
      }
    } else {
      //非提交／保存时需要对象引用，这样一些控件的绑定关系不会断
      custFormValues = this.props.params.applicationOID ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    }

    custFormValues.map(item => {
      Object.keys(values).map(key => {
        if (key === item.fieldOID || key === item.formValueOID) {
          item = customField.formatFormValue(item, values[key], this.state.formInfo.formCode);
        }
      })
    });
    //保存／提交前要去除塞入的连选日期控件
    let rangePickerIndex = -1;
    custFormValues.map((item, index) => {
      if (item.messageKey === 'range_picker') {
        rangePickerIndex = index;
      }
      try {
        if (item.messageKey === 'select_company' && item.value) {
          if (typeof (item.value) === 'string') {
            item.value = JSON.parse(item.value)[0].companyOID;
          } else if (typeof (item.value) === 'object') {
            item.value = item.value[0].companyOID
          }
        }
        if (item.messageKey === 'input' && (item.fieldName === '默认额度' || item.fieldName === '当前额度' || item.fieldName === '政策规定额度' || item.fieldName === '申请额度')) {
          item.value = Number(item.value.replace(',', ''))
        }
        if (item.fieldCode === 'quota') {
          item.value = Number(item.value.replace(',', ''))
        }
        if (item.messageKey === 'select_cost_center' && item.value) {
          if (typeof (item.value) === 'string') {
            item.value = JSON.parse(item.value)[0].costCenterItemOID;
          } else if (typeof (item.value) === 'object') {
            item.value = item.value[0].costCenterItemOID
          }
        }
      } catch (e) {
        // value不是JSON字符串不需要特殊处理
      }
    });
    if (rangePickerIndex !== -1 && isClearRange) {
      custFormValues.splice(rangePickerIndex, 1);
    }
    return custFormValues
  };

  //保存／提交前处理单据数据
  processValues = (params) => {
    const { jobId } = this.state;
    //新建的时候的特殊处理
    if (!this.props.params.applicationOID) {
      params.remark = ''; //新建时要把表单带出的remark清空，这不是单据的remark
      if (this.props.params.ifProxy === '1') {
        params.applicantOID = this.props.params.applicantOID; // 代提申请单时，申请人要以路由里带过来的上司的userOID为准
      } else {
        params.applicantOID = this.props.user.userOID; //新建时要把applicantOID填上，现在customValues里去除了申请人控件
      }
      params.jobId = jobId; //新建的时候要赋值单据岗位id
    }
    if (this.isSetCloseEnabled) {//设置自动停用日期
      params.closeEnabled = 1;
      params.closeDate = this.closeDate;
    }
  }

  //提交前检查组合控件的表单值验证,异步方法
  submitSaveValidateCombinationForm() {
    let isEdit = this.props.params.applicationOID ? true : false;
    let customFormFields = isEdit ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let isHaveValidate = false;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
        if (info) {
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({ [!isEdit ? item.fieldOID : item.formValueOID]: info })
          isHaveValidate = true;
        }
      }
    });
    return isHaveValidate;
  }
  //组合表单验证结果
  combinationFormValidateResult() {
    let isEdit = this.props.params.applicationOID ? true : false;
    let customFormFields = isEdit ? this.state.info.custFormValues : this.state.formInfo.customFormFields;
    let isPassValid = true;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
        if (info) {
          isPassValid = !isPassValid || info.isPassValid;
        }
      }
    });
    return isPassValid;
  }
  //008礼品申报单保存&提交前验证附件是否为空
  checkFileUpload = (data,gifmessage) => {
    let isOk = true;
    let GiftDeclareValue = getGiftDeclareValue(data, gifmessage);
    // console.log("GiftDeclareValue", GiftDeclareValue)
    if(GiftDeclareValue.giftObtainChannel===1 &&GiftDeclareValue.giftObtainChannelGiftApplyBillFileJson ==='[]'){
      message.warning('请上传支持性文件!')
        isOk = false;
    }
    for (const giftHandleTypeIndex of [1, 2, 3, 4, 5, 6]) {
      const key = `giftHandleType2_4_${giftHandleTypeIndex}`;
      if(GiftDeclareValue[`${key}Checked`]!==""&&GiftDeclareValue[`${key}GiftApplyBillFileJson`]==='[]'){
        message.warning('请上传支持性文件!')
        isOk = false;
      }
    }
    this.setState({ saveLoading: false, submitLoading: false });
    return isOk;
  }
  //保存&提交前验证custFormValues
  custFormValuesValidate = (custFormValues) => {
    const { formType, editTicketInfoVisible, formInfo } = this.state;
    const { formCode } = formInfo;
    let isOk = true;
    //校验开始日期是否小于结束日期
    let startDateValue = null;
    let endDateValue = null;
    let isHasFatherCostCenter = false; //父级成本中心是否有值
    custFormValues.map(item => {
      if (item.messageKey === 'select_cost_center' && item.dataSource && JSON.parse(item.dataSource || '{}').type === 'father' && item.value) {
        isHasFatherCostCenter = true;
      }
    });
    custFormValues.map(item => {
      if (item.messageKey === 'start_date' || item.fieldCode === 'startDatedaili') {
        startDateValue = item.value;
      }
      if (item.messageKey === 'end_date' || item.fieldCode === 'endDatedaili' || item.fieldCode === 'endDatedali') {
        endDateValue = item.value;
      }
      if (item.messageKey === 'select_cost_center' && item.dataSource && JSON.parse(item.dataSource || '{}').type === 'son' && !item.value && isHasFatherCostCenter) {
        message.error(messages('common.please.select')/*请选择*/ + item.fieldName);
        isOk = false;
      }
      // task#37964 团体申请单 参与人必须大于等于2
      if (formCode === 'MCD3001' && item.messageKey === 'select_participant') {
        const participantValArr = JSON.parse(item.value || '[]');
        if (participantValArr.length < 2) {
          message.error(messages('mcd.group.participant.min'/*请至少选择2位参与人*/));
          isOk = false;
        }
      }
      //校验预算分摊必填 & 校验自动生成的预算费用类型和金额必填
      //校验报销类型必填的情况下是否有选值
      //差旅单，第一个操作页面没有预算明细控件，不对预算明细进行校验
      if (item.messageKey === 'budget_detail' && item.value && !(formType === 2001 && !editTicketInfoVisible)) {
        let budgetList = JSON.parse(item.value) ? JSON.parse(item.value).budgetDetail : [];
        budgetList.map(budget => {
          if (budget.apportionmentDTOList && budget.apportionmentDTOList.length && isOk) {
            let i = 0;
            for (i; i < budget.apportionmentDTOList.length; i++) {
              //判断分摊项是否有填, 校验部门必填，成本中心是否必填根据required字段判断，父成本中心有值，则子成本中心必填
              let j = 0;
              let isHasApportionItem;
              for (j; j < budget.apportionmentDTOList[i].costCenterItems.length; j++) {
                if (!budget.apportionmentDTOList[i].costCenterItems[j].costCenterOID
                  && budget.apportionmentDTOList[i].costCenterItems[j].type === 1
                  && budget.apportionmentDTOList[i].costCenterItems[j].isApportionItem
                  && isOk) {
                  message.error(messages('request.key521')/*有未填写的分摊项*/);
                  isOk = false;
                }
                if (!budget.apportionmentDTOList[i].costCenterItems[j].costCenterOID
                  && budget.apportionmentDTOList[i].costCenterItems[j].type === 0
                  && budget.apportionmentDTOList[i].costCenterItems[j].required
                  && budget.apportionmentDTOList[i].costCenterItems[j].isApportionItem
                  && isOk) {
                  message.error(messages('request.key521')/*有未填写的分摊项*/);
                  isOk = false;
                }
                if (budget.apportionmentDTOList[i].costCenterItems[j].isApportionItem) {
                  isHasApportionItem = true;
                }
              }
              if (!isHasApportionItem) {
                message.error(messages('my-account.key81'/*费用分摊中的明细信息不完整，请完善*/));
                isOk = false;
              }
            }
          }
          if (!budget.expenseTypeOID && isOk) {
            message.error(messages('request.key557')/*请选择费用类型*/);
            isOk = false;
          }
          if (!budget.amount && isOk) {
            message.error(messages('request.key558')/*请填写金额*/);
            isOk = false;
          }
          if (budget.data && budget.data.length && budget.data[0].required && !budget.data[0].value && isOk) {
            message.error(messages('request.key617', { arg1: budget.data[0].name })/*请选择{arg1}*/);
            isOk = false;
          }
        });
      }
      // 公务卡额度调整申请单 申请金额上限1000w 判断
      if (item.messageKey === 'number' && item.fieldCode === 'quota' && item.value && item.value > 10000000) {
        message.error(messages('finance-setting.key501', { arg1: '10,000,000' }/*金额上限为{arg1}*/));//金额上限为{arg1}
        isOk = false;
      }
    });
    console.log("startDateValue", startDateValue)
    console.log("endDateValue", endDateValue)
    if (startDateValue && endDateValue && moment(startDateValue).isAfter(endDateValue)) {
      message.error(messages('request.key178'/*开始时间不能晚于结束时间*/));//开始时间不能晚于结束时间
      isOk = false;
    }
    if (!['SQ018', 'SQ019', 'SQ017', 'MCD1001', 'MCD2001', 'MCD3001'].includes(formCode)) {
      if (startDateValue && endDateValue && moment(startDateValue).format('YYYY-MM-DD') === moment(endDateValue).format('YYYY-MM-DD')) {
        message.error(messages('request.key809'/*开始时间和结束时间不能为同一天*/));//开始时间和结束时间不能为同一天
        isOk = false;
      }
    }
    return isOk;
  };

  /**
   * 先校验停用日期是否早于当前时间， 然后保存
   */
  //保存时校验停用日期是否早于当前时间
  judgeDisableDate = (params, isGoAutoLoan) => {
    if (this.isSetCloseEnabled && this.closeDate) {
      let date = new Date();
      date = moment(date).format('YYYY-MM-DD');
      let disableDate = moment(this.closeDate).format('YYYY-MM-DD');
      if (moment(disableDate).isBefore(date)) {
        //弹框提示是否继续提交
        Modal.confirm({
          title: messages('request.key585')/*关闭时间早于当前时间*/,
          content: <div>
            <p>{messages('request.key586')/*您仍可以提交，但审批通过后，不可报销*/}</p>
          </div>,
          okText: messages('common.submit')/*提交*/,
          cancelText: messages('request.key194')/*返回修改*/,
          onOk: () => this.handleSaveStep1(params, isGoAutoLoan),
          onCancel: () => { },
        });
      } else {
        this.handleSaveStep1(params, isGoAutoLoan);
      }
    } else {
      this.handleSaveStep1(params, isGoAutoLoan);
    }
  };

  //提交前校验预算上的默认分摊是否和表单上的部门，成本中心控件一致
  checkApportion = (custFormValues) => {
    let valueOIDList = [];
    let defaultApportionList = []; //预算明细上每个费用的默认分摊
    let isHasDepartment = false;
    let isDifferent = false; //费用上默认分摊是否和表头的字段不一致
    custFormValues.map((item, index) => {
      if (item.messageKey === 'select_department') {
        isHasDepartment = true;
        if (item.value) {
          valueOIDList.push(item.value);
        }
      }
      if (item.messageKey === 'select_cost_center' && item.value) {
        valueOIDList.push(item.value);
      }
      if (item.messageKey === 'budget_detail' && item.value) {
        let expenseBudgetList = JSON.parse(item.value).budgetDetail || [];
        expenseBudgetList.map((budget, budgetIndex) => {
          if (budget.apportionmentDTOList && budget.apportionmentDTOList.length) {
            defaultApportionList.push(budget.apportionmentDTOList[0].costCenterItems);
          }
        });
      }
    });
    defaultApportionList.map((costCenterItems) => {
      let defaultApportionOIDList = []; //每一个默认分摊的数据
      costCenterItems.map(defaultApportion => {
        if (defaultApportion.type === 1 && isHasDepartment && valueOIDList.indexOf(defaultApportion.costCenterOID) === -1) {
          isDifferent = true;
        }
        if (defaultApportion.type === 0 && defaultApportion.costCenterOID && valueOIDList.indexOf(defaultApportion.costCenterOID) === -1) {
          isDifferent = true;
        }
        if (((defaultApportion.type === 1 && isHasDepartment) || defaultApportion.type === 0) && defaultApportion.costCenterOID) {
          defaultApportionOIDList.push(defaultApportion.costCenterOID);
        }
      });
      if (defaultApportionOIDList.length !== valueOIDList.length) {
        isDifferent = true;
      }
    });
    return isDifferent;
  };

  //差旅单保存或提交前处理预算明细控件
  processBeforeSaveOrSubmit = (custFormValues) => {
    const { isHasTravelBudgetDetail, travelBudgetDetailObj } = this.state;
    if (isHasTravelBudgetDetail) {
      custFormValues.map((valueItem, index) => {
        if (valueItem.messageKey === 'budget_detail') {
          valueItem.value = travelBudgetDetailObj ? JSON.stringify(travelBudgetDetailObj) : "";
        }
      });
    }
  };

  //部门，成本中心不启用分摊时，值要和表头的值一致，表头部门没有值的情况下，塞岗位的部门
  processApportionment = (custFormValues) => {
    const { profile } = this.props;
    const { jobInfo } = this.state;
    let departName = '';
    let departOID = jobInfo.departmentOID;
    let pathDepth = 1;
    if (profile && profile['department.full.path.disabled'] && jobInfo.departmentName) {
      let array = jobInfo.departmentName.split('|');
      departName = array[array.length - 1];
      pathDepth = array.length;
    } else {
      departName = jobInfo.departmentName;
    }
    custFormValues.map((valueItem, index) => {
      if (valueItem.messageKey === 'budget_detail' && valueItem.value) {
        valueItem.value = JSON.parse(valueItem.value);
        valueItem.value.budgetDetail && valueItem.value.budgetDetail.map(expense => {
          if (expense.apportionmentDTOList && expense.apportionmentDTOList.length) {
            let defaultCostCenterItems = JSON.parse(JSON.stringify(expense.apportionmentDTOList[0].costCenterItems));
            expense.apportionmentDTOList.map((apportionmentDTO, index) => {
              apportionmentDTO.costCenterItems.map(costCenterItem => {
                //type 0成本中心 1部门
                if (costCenterItem.type === 0 && !costCenterItem.isApportionItem) {
                  let item = this.getItemInCostCenterItems(costCenterItem.costCenter, defaultCostCenterItems);
                  costCenterItem.costCenterOID = item.costCenterOID;
                  costCenterItem.name = item.name;
                }
                if (costCenterItem.type === 1 && !costCenterItem.isApportionItem) {
                  let item = this.getItemInCostCenterItems(costCenterItem.costCenter, defaultCostCenterItems);
                  if (item.costCenterOID) {
                    costCenterItem.costCenterOID = item.costCenterOID;
                    costCenterItem.name = item.name;
                    costCenterItem.pathDepth = item.pathDepth;
                  } else {
                    costCenterItem.costCenterOID = departOID;
                    costCenterItem.name = departName;
                    costCenterItem.pathDepth = pathDepth;
                  }
                }
              });
            });
          }
        });
        valueItem.value = JSON.stringify(valueItem.value);
      }
    });
  };

  /**
   *
   * @param id  分摊项上的costCenter
   * @param defaultCostCenterItems 分摊项列表
   * @returns 根据id找到的分摊项object
   */
  getItemInCostCenterItems = (id, defaultCostCenterItems) => {
    let item = {};
    defaultCostCenterItems.map(apportionItem => {
      if (apportionItem.costCenter === id) {
        item = JSON.parse(JSON.stringify(apportionItem));
      }
    });
    return item;
  };

  //保存 保存为草稿
  //isGoAutoLoan 保存成功后是否跳转新建借款单
  handleSave = (isGoAutoLoan) => {
    if (this.submitSaveValidateCombinationForm()) {
      //组合子表单验证信息传递需要时间
      setTimeout(() => this.delayHandleSave(isGoAutoLoan), 10);
    }
    else {
      this.delayHandleSave(isGoAutoLoan);
    }
  };
  //处理保存
  delayHandleSave = (isGoAutoLoan) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!this.combinationFormValidateResult()) {
        return;
      }
      if (this.state.formInfo.formCode === "SQ008") {
        //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
        const { info, formInfo, formType, referenceApplicationOID, travelItinerarys } = this.state;
        const { loginUser } = this.props;
        const { formCode } = formInfo;
        let params = this.props.params.applicationOID ? JSON.parse(JSON.stringify(info)) : JSON.parse(JSON.stringify(formInfo));
        params.custFormValues = this.getCustFormValues(values, true);
        if (formType === 2001) {
          this.processBeforeSaveOrSubmit(params.custFormValues);
        }
        this.processApportionment(params.custFormValues);
        if (!this.custFormValuesValidate(params.custFormValues)) {
          return;
        }
        params.applicant = null;
        params.referenceApplicationOID = referenceApplicationOID;
        if (this.props.form.getFieldsValue().addSign) {
          const addSignVal = this.props.form.getFieldsValue().addSign;
          const TMCFiled = params.custFormValues.filter(item => item.fieldCode === 'TMC');
          let TMCVal;
          if (TMCFiled && TMCFiled.length && TMCFiled[0]) {
            TMCVal = TMCFiled[0].value;
          }
          params.countersignApproverOIDs = (typeof addSignVal === 'string') ? [addSignVal] : addSignVal;
          const uID = loginUser.userOID;
          if (TMCVal === '2' && ['MCD3001', 'OFFLINE_HOTEL_CONFIRMATION_FORM', 'OFFLINE_FLIGHT_CONFIRMATION_FORM'].indexOf(formCode) > -1 && params.countersignApproverOIDs[0] !== uID) {
            params.countersignApproverOIDs.unshift(uID);
          }
        }
        this.processValues(params);
        this.judgeDisableDate(params, isGoAutoLoan);
      } else {
        if (!err) {
          //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
          const { info, formInfo, formType, referenceApplicationOID, travelItinerarys } = this.state;
          const { loginUser } = this.props;
          const { formCode } = formInfo;
          let params = this.props.params.applicationOID ? JSON.parse(JSON.stringify(info)) : JSON.parse(JSON.stringify(formInfo));
          params.custFormValues = this.getCustFormValues(values, true);
          if (formType === 2001) {
            this.processBeforeSaveOrSubmit(params.custFormValues);
          }
          this.processApportionment(params.custFormValues);
          if (!this.custFormValuesValidate(params.custFormValues)) {
            return;
          }
          params.applicant = null;
          params.referenceApplicationOID = referenceApplicationOID;
          if (this.props.form.getFieldsValue().addSign) {
            const addSignVal = this.props.form.getFieldsValue().addSign;
            const TMCFiled = params.custFormValues.filter(item => item.fieldCode === 'TMC');
            let TMCVal;
            if (TMCFiled && TMCFiled.length && TMCFiled[0]) {
              TMCVal = TMCFiled[0].value;
            }
            params.countersignApproverOIDs = (typeof addSignVal === 'string') ? [addSignVal] : addSignVal;
            const uID = loginUser.userOID;
            if (TMCVal === '2' && ['MCD3001', 'OFFLINE_HOTEL_CONFIRMATION_FORM', 'OFFLINE_FLIGHT_CONFIRMATION_FORM'].indexOf(formCode) > -1 && params.countersignApproverOIDs[0] !== uID) {
              params.countersignApproverOIDs.unshift(uID);
            }
          }
          this.processValues(params);
          this.judgeDisableDate(params, isGoAutoLoan);
        }
      }
    });
  }


  handleSaveStep1 = (params, isGoAutoLoan) => {
    const { formType, formInfo } = this.state;
    this.setState({ saveLoading: true });
    if (formType === 2001) {// wjk add 18 04 16 差旅保存分支
      this.toSaveTravelRequest(params, 'save', isGoAutoLoan);
      return;
    }
    let getType =
      formType === 2002 ? 'saveExpenseRequest' :
        formType === 2003 ? 'saveBookerRequest' :
          formType === 2005 ? 'saveLoanRequest' : '';
    requestService[getType](params).then((res) => {
       /**
       * 如果是礼品申报单，再保存礼品申报单详情
       */
      if (formInfo.formCode === "SQ008") {
        return giftDeclareService
          .saveGiftDeclare(
            getGiftDeclareValue(res.data, this),
            !!this.state.info.businessCode
          )
          .then((res2) => {
            return res
          });
      } else {
        return res;
      }
    }).then(res => {
      // //提交前检查附件是否为空
      // if(formInfo.formCode === "SQ008"){
      //   if(!this.checkFileUpload(res.data, this)){
      //     return ;
      //   }
      // }
      let info = res.data
      this.setState({ saveLoading: false });
      message.success(messages('common.save.success', { name: '' }));
      if (isGoAutoLoan === true) {
        this.goCreateLoan(res.data.applicationOID);
      } else {
        if (['SQ002', 'SQ003', 'SQ004'].includes(formInfo.formCode)) {
          menuRoute.goForm(this, formInfo.formCode, {
            action: 'detail',
            params: {
              formOID: info.formOID,
              applicationOID: info.applicationOID,
              id: info.id,
            }
          })
        } else {
          this.goBack();
        }
      }
    }).catch(e => {
      console.error(e)
      this.setState({ saveLoading: false });
      let error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(`${messages('common.save.filed')}，${error.validationErrors[0].message}`)
      } else {
        message.error(`${messages('common.save.filed')}，${error.message}`)
      }
    });
  };


  //判断是否有重复的差补明细
  isHaveRepeatSubsidy = (params, type) => {
    let isHaveRepeat = this.state.isRepeatSubsidy;
    let setOption = this.props.profile['allowance.reduplicate.treatment'] ? this.props.profile['allowance.reduplicate.treatment'] : false;
    setOption = setOption ? (setOption === 1001 ? 'warn' : 'error') : 'warn'; //没有配置的时候默认为'警告'
    if (isHaveRepeat) {
      if (setOption) {
        if (setOption === 'error') {
          Modal.error({
            title: messages('request.key179'/*有重复差补明细*/),/*'有重复差补明细',*/
          });
          this.setState({ loading: false, saveLoading: false, submitLoading: false });
        } else {
          Modal.confirm({
            title: messages('request.key179'/*有重复差补明细*/),/*'有重复差补明细',*/
            okText: messages('request.key180'/*继续提交*/),/*'继续提交'*/
            cancelText: messages('request.key181'/*返回*/),
            onOk: () => {
              this.toSaveTravelRequest(params, type);
            },
            onCancel: () => {
              this.setState({ loading: false, saveLoading: false, submitLoading: false });
            }
          });
        }
      } else {
        Modal.confirm({
          title: messages('request.key182'/*错误！*/),
          content: messages('request.key183'/*profile中无(allowance.reduplicate.treatment)配置字段,是否继续提交?*/),
          okText: messages('request.key180'/*继续提交*/),/*'继续提交'*/
          cancelText: messages('request.key181'/*返回*/),
          onOk: () => {
            this.toSaveTravelRequest(params, type);
          },
          onCancel: () => {
            this.setState({ loading: false, saveLoading: false, submitLoading: false });
          }
        });
      }
    } else {
      this.toSaveTravelRequest(params, type);
    }
  }

  /**
   * 差旅申请单保存/提交
   * @param params 对象  提交、保存的参数
   * @param type 字符串 区分保存还是提交类型 ‘save’or ‘submit’
   * @param isGoAutoLoan 保存成功后是否跳转到新建借款单页面
   */
  toSaveTravelRequest = (params, type, isGoAutoLoan) => {
    let partiOid = "";
    let indexOf = 0;
    let formVs = params.custFormValues;
    let currentStatus = this.props.params.applicationOID ? 'edit' : 'create';
    let isCanSubmit = travelUtil.customFormChecked(formVs);
    if (!isCanSubmit) {
      this.setState({ loading: false, saveLoading: false, submitLoading: false });
      return;
    }
    formVs.map((cus, index) => {//通过messageKey拿到对应表单的key，applicationOID存在为编辑状态
      if (cus.messageKey === "select_participant") {
        partiOid = this.props.params.applicationOID ? cus.formValueOID : cus.fieldOID;
        indexOf = index;
      }
    });
    let isSetSelectParticipant = false;//是否配置了参与人字段，如果配置了且是开启内部参与人，则需要校验
    params.custFormValues.map(item => {
      if (item.messageKey === 'select_participant') {
        isSetSelectParticipant = true;
        if (item.fieldContent) {
          isSetSelectParticipant = JSON.parse(item.fieldContent).isUse;
        }
      }
    });
    if (isSetSelectParticipant) {
      this.setState({ loading: true });
      travelService.travelValidate(params, this.props.language, this.customFormFieldsOrigin).then(res => {//参与人权限校验
        let partis = this.props.form.getFieldValue(partiOid);
        let showName = "";
        res.data.map(item => {
          if (item.errorDetail) {
            showName = `${showName} ${item.fullName}`;
          }
        });
        if (showName) {
          //弹框提示是否删除不在权限内的参与人
          if (this.state.info.sourceApplicationOID) {
            this.setState({ saveLoading: false, loading: false, submitLoading: false });
            Modal.warn({
              title: messages('request.key173'/*提示*/),
              content: <div>
                <p>{messages('request.key454', { arg1: showName }/*{arg1} 不符合数据权限，请检查或联系系统管理员*/)}</p>
              </div>,
              okText: messages('request.key175'/*取消*/),
            });
          } else {
            const { editTicketInfoVisible } = this.state;
            //判断在详情编辑页还是详情展示页，只有编辑页保存提交才能自动删除参与人，展示页则提醒去删除
            if (editTicketInfoVisible) { //展示页
              Modal.confirm({
                title: messages('request.key173'/*提示*/),
                content: <div>
                  <p>{messages('mcd.invalid.partis', { arg1: showName }/*{arg1} 不在可选人员范围内，去编辑？*/)}</p>
                </div>,
                okText: messages('common.ok')/*确认*/,
                cancelText: messages('request.key175'/*取消*/),
                onOk: () => { this.hideLoading(); this.goTravelEdit(); },
                onCancel: () => this.hideLoading()
              });
            } else { //编辑页
              Modal.confirm({
                title: messages('request.key173'/*提示*/),
                content: <div>
                  <p>{messages('request.key455', { arg1: showName }/*{arg1} 不在可选人员范围内，是否删除以上人员?*/)}</p>
                  {this.state.total > 0 && <p style={{ fontSize: 12 }}>{messages('request.key184'/*更改参与人将清空差补，您要重新添加差补.*/)}</p>}
                </div>,
                okText: messages('common.delete')/*删除*/,
                cancelText: messages('request.key175'/*取消*/),
                onOk: () => this.deletePartis(res, partis, params, type, currentStatus),
                onCancel: () => { this.setState({ saveLoading: false, loading: false, submitLoading: false }); }
              });
            }
          }
        } else {
          this.travelParams = params;
          this.cancelDelPartis(params, type, currentStatus, isGoAutoLoan);//如果参与人员都符合权限，不弹框默认走取消弹框函数。
        }
      }).catch(err => {
        this.setState({ saveLoading: false, loading: false, submitLoading: false });
        let error = err.response.data;
        if (error.validationErrors && error.validationErrors.length) {
          if (error.validationErrors[0].externalPropertyName) {
            switch (error.validationErrors[0].externalPropertyName) {
              case '2010': //申请人为空
                message.error(messages('request.key185'/*申请人为空.*/));
                break;
              case '2011': //部门为空
                message.error(messages('request.key186'/*部门为空.*/));
                break;
              case '2012': //成本中心为空
                message.error(messages('request.key187'/*成本中心为空.*/));
                break;
              default: message.error(messages('request.key188'/*出错了，请联系管理员*/));
            }
          }
        } else {
          message.error(`${messages('common.save.filed')}，${error.message}`)
        }
      })
    } else {
      this.travelParams = params;
      this.cancelDelPartis(params, type, currentStatus, isGoAutoLoan);
    }
  };

  //进度条数值控制器
  percentPlus = () => {
    this.percentNum = this.percentNum + 9;
    this.setState({ percent: this.percentNum > 100 ? 100 : this.percentNum });
    if (this.percentNum <= 99) {
      setTimeout(this.percentPlus, 10);
    }
  };

  /**
   * 保存和提交的流程
   * @param params 保存和提交的结构体数值
   * @param type   区分保存(save)还是提交(submit)动作
   * @param status 区分是新建（create）还是编辑（edit）
   * @param isGoAutoLoan 保存成功后是否跳转到新建借款单页面
   */
  cancelDelPartis = (params, type, status, isGoAutoLoan) => {
    this.setState({ loading: true });
    const { needClearSubsidy } = this.state;
    if (type === 'save') {//保存走这里
      if (status === 'create') {
        this.setState({ isFirstSave: true });
        params.travelApplication = {};
        //设置行程管控
        params.travelApplication.manageType = params['customFormPropertyMap']['application.property.manage.type'];
      }
      if (this.state.travelItinerarys.length > 0) {
        params.travelApplication.travelItinerarys = [];
        params.travelApplication.travelItinerarys = this.state.travelItinerarys;
      }
      params.travelApplication.totalBudget = this.state.totalBudget;
      params.applicant = null;
      if (needClearSubsidy) {
        this.clearSubsidyReal(() => {
          this.handleRealSave(params, isGoAutoLoan);
        });
      } else {
        this.handleRealSave(params, isGoAutoLoan);
      }
    } else {//提交走这里：
      if (status === 'create') {
        message.error(messages('request.key191'/*请先保存!*/));
        this.setState({ submitLoading: false, loading: false });
        return;
        /*下面注释三行不可删除，以后需求可能会不保存直接操作提交，如果这样只需删除上面三行，并取消注释*/
        // params.travelApplication = {};
        //设置行程管控
        // params.travelApplication.manageType = params['customFormPropertyMap']['application.property.manage.type'];
      }
      //提交时校验行程是否必须添加
      if (type === 'submit' && this.state.subsidyCtrl.itineraryRequire && !this.state.isHaveRoute) {
        message.warn(messages('request.key192'/*请添加行程*/));
        this.setState({ submitLoading: false, loading: false });
        return;
      }
      params.applicant = null;
      params.travelApplication.totalBudget = this.state.totalBudget;
      if (this.state.subsidyCtrl.isBudgetCheck) {//是否需要预算校验
        this.setState({ loading: true, submitLoading: true, percent: 0, budgeting: true });
        //开始校验
        this.percentNum = 0;
        this.percentPlus();
        travelService.travelBudgetChecked(params).then(c => {
          this.setState({ percent: 100, budgeting: false });
          if (c.data) {
            if (status === 'create') {
              this.executeTravelSubmit();
            } else {
              this.checkedItinerary(params)
            }
          } else {
            Modal.confirm({
              title: messages('request.key193'/*超预算*/),
              content: <div>{c.data}</div>,
              okText: messages('request.key180'/*继续提交*/),
              cancelText: messages('request.key194'/*返回修改*/),
              onOk: () => {
                this.checkedItinerary(params)
              },
              onCancel: () => {
                this.percentNum = 0;
                this.setState({ submitLoading: false, loading: false });
              },
            })
          }
        }).catch(err => {
          this.setState({ percent: 100, budgeting: false, loading: false, submitLoading: false });
          message.error(messages('request.key195'/*预算校验失败:*/) + `${err.response.data.message}`)
        })
      } else {
        //检查行程中有哪几种，是否弹框统一订票
        if (status === 'create') {
          this.executeTravelSubmit();
        } else {
          this.checkedItinerary(params);
        }
      }
    }
  };

  handleRealSave = (params, isGoAutoLoan) => {
    travelService.saveTravelRequest(params).then(res => {
      this.setState({ loading: false, saveLoading: false });
      this.props.params.applicationOID = res.data.applicationOID;
      message.success(messages('request.key189'/*已保存*/));
      if (!this.state.editTicketInfoVisible) { //保存申请单头部信息后需要拿到申请单详情显示信息
        requestService.getRequestDetail(res.data.applicationOID).then(res => {
          let valuesOnlyForShow = JSON.parse(JSON.stringify(res.data.custFormValues));
          let isHasTravelBudgetDetail = false;
          let travelBudgetDetailObj = null;
          valuesOnlyForShow.map((valueItem, index) => {
            if (valueItem.messageKey === 'budget_detail') {
              isHasTravelBudgetDetail = true;
              travelBudgetDetailObj = valueItem.value ? JSON.parse(valueItem.value) : null;
            }
          });
          this.setApplicantDisable(res.data.custFormValues);
          this.processTravelDate(res.data, 'edit');
          res.data.custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
          res.data.custFormValues.map(item => {
            if (item.messageKey === 'select_participant' && item.value) {
              let arr = [];
              JSON.parse(item.value).map(detail => {
                let newItem = {
                  userOID: detail.userOID,
                  fullName: detail.fullName,
                  participantOID: detail.participantOID
                };
                arr.push(newItem);
              });
              item.value = JSON.stringify(arr);
            }
          })
          this.copyDefaultCust(res, 'edit');
          this.setState({
            info: res.data,
            valuesOnlyForShow,
            isHasTravelBudgetDetail,
            travelBudgetDetailObj,
            travelItinerarys: res.data.travelApplication.travelItinerarys,
            travelElementServiceName: res.data.travelApplication.supplierServiceName,
            defaultValues: res.data.custFormValues,
          }, () => {
            this.setState({ formIsChange: 'false', editTicketInfoVisible: true, isSaveBtnClicked: true });
          });
        })
      } else { //保存行程信息后直接返回到列表页
        if (isGoAutoLoan === true) {
          this.goCreateLoan(res.data.applicationOID);
        } else {
          this.goBack();
        }
      }
    }).catch(err => {
      this.setState({ loading: false, saveLoading: false });
      const errMsg = err.response.data.message || '';
      const errCode = err.response.data.errorCode;
      if (errCode === '11005' || errCode === '11004') {
        const errArr = errMsg.split('<br/>') || [];
        //弹框提示
        Modal.info({
          title: messages('request.key173'/*提示*/),
          content: <div>
            {errArr.map(e => (<p>{e}</p>))}
          </div>,
          okText: messages('common.ok')/*确认*/,
          width: '800px'
        });
      } else {
        message.error(messages('request.key190'/*操作失败:*/) + `${errMsg}`);
      }
    });
  }

  //检查行程数据，是否需要显示统一订票等操作
  checkedItinerary = (params) => {
    let { formInfo, info, isFlight, isTrain, isHotel, isDining, isFlightSwitch, isTrainSwitch, isHotelSwitch, isDiningSwitch } = this.state;
    let cfpm = formInfo && formInfo.customFormPropertyMap;
    travelService.getItinerary(this.props.params.applicationOID).then(res => {
      let it = res.data;
      let sub = this.state.subsidyCtrl;
      //初始化为false,然后再判断对应行程统一订票是否展示 bugfix 42556
      sub.flight = false;//是否显示飞机统一订票
      sub.flightPlatform = false; //机是否有支持订票平台的机票行程
      sub.train = false;//。。。。火车统一订票
      sub.hotel = false;//是否显示酒店统一订票
      sub.dining = false; //是否显示用餐统一订票
      sub.didi = false; //是否显示用车统一订票 用车只有各自订票
      if (it['FLIGHT'] && it['FLIGHT'].length > 0) {
        it['FLIGHT'].map(flight => {
          //设置是否有非支持订票平台的机票行程
          if (!flight.supplierPlatFormEnable) {
            if (flight.supplierConfig && JSON.parse(flight.supplierConfig) && JSON.parse(flight.supplierConfig)[0].pushType !== 'NEVER' && cfpm['ca.travel.bookingpreference'] !== 'OnlyIndividual') {
              sub.flight = true;
            }
          }
          //设置是否有支持订票平台的机票行程
          if (flight.supplierPlatFormEnable && cfpm['ca.travel.bookingpreference'] !== 'OnlyIndividual') {
            sub.flightPlatform = true;
          }
        });
        //获取最大机票数
        travelService.getMaxFlight(this.props.params.applicationOID).then(f => {
          this.setState({ maxFlight: f.data });
        });
      }
      if (it['HOTEL'] && it['HOTEL'].length > 0) {
        it['HOTEL'].map(hotel => {
          if (hotel.supplierConfig && JSON.parse(hotel.supplierConfig) && JSON.parse(hotel.supplierConfig)[0].pushType !== 'NEVER' && cfpm['ca.travel.hotel.bookingpreference'] !== 'OnlyIndividual') {
            sub.hotel = true;
          }
        });
        let outNum = travelUtil.getFormHeadValue(params.custFormValues, 'out_participant_num');
        this.setState({ randomHotel: true });
        const formHeadMaxNum = travelUtil.getFormHeadValueByCode(params.custFormValues, 'maxnum');
        //获取最大房间数
        console.log('------获取最大房间数 updateHotel-----')
        if (formHeadMaxNum && typeof formHeadMaxNum === 'string') {
          this.setState({ maxHotel: formHeadMaxNum, randomHotel: false });
          it['HOTEL'].map(room => {
            if (room.hotelItineraryOID && formHeadMaxNum && room.roomNumber !== formHeadMaxNum) {
              room.roomNumber = formHeadMaxNum;
              travelService.updateHotel(room);//最大房间数与当前参与人配备的最大房间数不一样则更新。
            }
          })
        } else {
          travelService.getMaxRoom(outNum, travelUtil.getFormHeadValue(params.custFormValues, 'select_participant')).then(h => {
            this.setState({ maxHotel: h.data, randomHotel: false });
            it['HOTEL'].map(room => {
              if (room.hotelItineraryOID && h.data.maxRoomNumber && room.roomNumber !== h.data.maxRoomNumber) {
                room.roomNumber = h.data.maxRoomNumber;
                travelService.updateHotel(room);//最大房间数与当前参与人配备的最大房间数不一样则更新。
              }
            })
          }).catch(err => {
            message.error(err.response.data.message);
            this.setState({ randomHotel: false });
          })
        }
      }
      if (it['TRAIN'] && it['TRAIN'].length > 0) {
        it['TRAIN'].map(train => {
          if (train.supplierConfig && JSON.parse(train.supplierConfig) && JSON.parse(train.supplierConfig)[0].pushType !== 'NEVER' && cfpm['ca.travel.train.bookingpreference'] !== 'OnlyIndividual') {
            sub.train = true;
          }
        });
      }
      if (it['DINING'] && it['DINING'].length > 0 && cfpm['ca.travel.dining.bookingpreference'] !== 'OnlyIndividual') {
        sub.dining = true;
      }
      if (it['DIDI'] && it['DIDI'].length > 0) {
        sub.didi = true;
      }
      sub.isShowModal = sub.flight || sub.flightPlatform || sub.train || sub.hotel || sub.dining || sub.didi;

      //处理统一订票默认值
      if (formInfo && formInfo.customFormPropertyMap && !info.sourceApplicationOID) {
        let maps = formInfo.customFormPropertyMap;
        let isBookingPreference = travelUtil.processUniformConfig('ca.travel.bookingpreference', maps, 'default');
        isFlightSwitch = travelUtil.processUniformConfig('ca.travel.bookingpreference', maps, 'switch');
        let isBookingPreferenceTrain = travelUtil.processUniformConfig('ca.travel.train.bookingpreference', maps, 'default');
        isTrainSwitch = travelUtil.processUniformConfig('ca.travel.train.bookingpreference', maps, 'switch');
        let isBookingPreferenceHotel = travelUtil.processUniformConfig('ca.travel.hotel.bookingpreference', maps, 'default');
        isHotelSwitch = travelUtil.processUniformConfig('ca.travel.hotel.bookingpreference', maps, 'switch');
        let isBookingPreferenceDining = travelUtil.processUniformConfig('ca.travel.dining.bookingpreference', maps, 'default');
        isDiningSwitch = travelUtil.processUniformConfig('ca.travel.dining.bookingpreference', maps, 'switch');
        if (sub.flight) {
          if (isBookingPreference) {
            info.travelApplication.uniformBooking = true;
            isFlight = true;
          } else {
            info.travelApplication.uniformBooking = false;
            isFlight = false;
          }
        }
        if (sub.train) {
          if (isBookingPreferenceTrain) {
            info.travelApplication.trainUniformBooking = true;
            isTrain = true;
          } else {
            info.travelApplication.trainUniformBooking = false;
            isTrain = false;
          }
        }
        if (sub.hotel) {
          if (isBookingPreferenceHotel) {
            info.travelApplication.hotelUniformBooking = true;
            isHotel = true;
          } else {
            info.travelApplication.hotelUniformBooking = false;
            isHotel = false;
          }
        }
        if (sub.dining) {
          if (isBookingPreferenceDining) {
            info.travelApplication.diningUniformBooking = true;
            isDining = true;
          } else {
            info.travelApplication.diningUniformBooking = false;
            isDining = false;
          }
        }
        this.setState({
          info,
          isFlight,
          isTrain,
          isHotel,
          isDining,
          isFlightSwitch,
          isTrainSwitch,
          isHotelSwitch,
          isDiningSwitch
        });
      }

      let originBookerOIDList = []; //原订票人oid，包含创建人，申请人，参与人
      sub.selectPerson = []; //添加前先置空
      sub.selectPerson.push({ name: params.createdName, oid: params.createdBy });//添加创建人
      originBookerOIDList.push(params.createdBy);
      let applicant = { name: params.applicantName, oid: params.applicantOID };
      sub.selectPerson.unshift(applicant);//添加申请人
      originBookerOIDList.push(params.applicantOID);
      //统一订票可包含订票专员，这个需求产品还没想好，这期不上
      let participantList = [];
      travelUtil.getFormHeadValue(params.custFormValues, 'select_participant').map(v => {
        originBookerOIDList.push(v.participantOID);
        participantList.push({ name: v.fullName, oid: v.participantOID });
      });
      sub.selectPerson.push(...participantList);
      sub.selectPerson = this.processUniformBooking(sub.selectPerson);
      this.setState({ subsidyCtrl: sub });
      //处理订票专员可选范围
      if (sub.flightPlatform) {
        sub.platformPerson = [];
        travelService.getUniformBooker().then(res => {
          if (res.data && res.data.length) {
            res.data.map(booker => {
              sub.platformPerson.push({ name: booker.userName, oid: booker.userOID });
            });
            this.setState({ subsidyCtrl: sub });
          }
        }).catch(err => {
          message.error(err.response.data.message);
        });
      }
      if (!sub.isShowModal) {//没有统一订票
        this.goSubmitTravel(true);
      }
    });
  };

  //统一订票人去重
  processUniformBooking = (bookerList) => {
    let buffBookerList = [];
    bookerList.map(booker => {
      let isExist = false;
      buffBookerList.map(buffBooker => {
        if (booker.oid === buffBooker.oid) {
          isExist = true;
        }
      });
      if (!isExist) {
        buffBookerList.push(booker);
      }
    });
    return buffBookerList;
  };

  //删除不在权限内的参与人

  deletePartis = (res, partis, params, type, status) => {
    res.data.map(item => {
      if (item.errorDetail) {
        partis && partis.map((p, ind) => {
          if (p.userOID === item.userOID) {
            partis.splice(ind, 1);
          }
        })
      }
    });
    if (this.state.total > 0)
      this.clearSubsidy();
    this.setState({
      saveLoading: false,
      submitLoading: false,
      loading: false,
    })
  };

  //清空差补
  clearSubsidy = () => {
    // this.setState({haveClear:true, loading: true});
    // travelService.deleteAllSubsidy(this.props.params.applicationOID).then(res => {
    //   message.success(messages('request.key196'/*已清空差补*/));
    //   this.setState({total: 0, haveClear: true, totalBudget: this.state.amount, loading: false});
    //   this.refreshBudget();
    // }).catch(err => {
    //   message.error(err);
    // })
    this.setState({ needClearSubsidy: true });
  };

  //真正清空差补
  clearSubsidyReal = (callback) => {
    this.setState({ haveClear: true, loading: true, needClearSubsidy: false });
    travelService.deleteAllSubsidy(this.props.params.applicationOID).then(res => {
      message.success(messages('request.key196'/*已清空差补*/));
      this.setState({ total: 0, haveClear: true, totalBudget: this.state.amount, loading: false });
      this.refreshBudget(callback);
    }).catch(err => {
      callback && this.setState({ loading: false, saveLoading: false })
      message.error(err);
    })
  };

  /**
   * 处理统一订票字段
   * @param boo 布尔值，是否不需要操作统一订票字段
   */
  goSubmitTravel = (boo) => {
    const { maxHotel, info, isFlight, isHotel, isTrain, isDining } = this.state;
    let { subsidyCtrl } = this.state;
    let isProcessFlight = true;//是否需要处理机票统一订票人
    let isProcessTrain = true;//是否需要处理火车统一订票人
    let isProcessHotel = true;//是否需要处理酒店统一订票人
    let isProcessDining = true;//是否需要处理用餐统一订票人
    if (info.sourceApplicationOID && info.travelApplication) {
      if (!info.travelApplication.uniformBooking) {
        isProcessFlight = false;
      }
      if (!info.travelApplication.hotelUniformBooking) {
        isProcessHotel = false;
      }
      if (!info.travelApplication.trainUniformBooking) {
        isProcessTrain = false;
      }
      if (!info.travelApplication.diningUniformBooking) {
        isProcessDining = false;
      }
    }
    if (boo) {//不需要处理统一订票字段直接提交
      this.executeTravelSubmit();
    } else {//需要处理统一订票字段，处理以后提交
      //如果是更改的单据，统一订票不可修改，不用再做处理
      if (subsidyCtrl.flight && isProcessFlight) {
        if (isFlight) {
          this.travelParams.travelApplication.uniformBooking = true;
          this.travelParams.travelApplication.bookingClerkOID = this.props.form.getFieldValue('bookingClerkOID');
        } else {
          this.travelParams.travelApplication.uniformBooking = false;
        }
      }
      //在处理完机票统一订票后，如果没有非订票平台的机票行程，机票的统一订票应该是非统一订票
      if (!subsidyCtrl.flight) {
        this.travelParams.travelApplication.uniformBooking = false;
      }
      if (subsidyCtrl.hotel && isProcessHotel) {
        if (isHotel) {
          this.travelParams.travelApplication.hotelUniformBooking = true;
          this.travelParams.travelApplication.hotelBookingClerkOID = this.props.form.getFieldValue('hotelBookingClerkOID');
        } else {//非同一定酒店 需设置合租人信息
          this.travelParams.travelApplication.hotelUniformBooking = false;
          let man = this.props.form.getFieldValue('travelHotelBookingMaleClerks');
          let women = this.props.form.getFieldValue('travelHotelBookingFemaleClerks');
          if (man && man.length === maxHotel.maleRoomNumber) {
            this.travelParams.travelApplication.travelHotelBookingMaleClerks = man;
          } else if (maxHotel.maleRoomNumber && maxHotel.maleRoomNumber > 0) {
            message.error(messages('request.key456', { arg1: maxHotel.maleRoomNumber }/*男性合住人需选{arg1}人*/));
            return;
          }
          if (women && women.length === maxHotel.femaleRoomNumber) {
            this.travelParams.travelApplication.travelHotelBookingFemaleClerks = women;
          } else if (maxHotel.femaleRoomNumber && maxHotel.femaleRoomNumber > 0) {
            message.error(messages('request.key457', { arg1: maxHotel.femaleRoomNumber }/*女性合住人需选{arg1}人*/));
            return;
          }
        }
      }
      if (subsidyCtrl.train && isProcessTrain) {
        if (isTrain) {
          this.travelParams.travelApplication.trainUniformBooking = true;
          this.travelParams.travelApplication.trainBookingClerkOID = this.props.form.getFieldValue('trainBookingClerkOID');
        } else {
          this.travelParams.travelApplication.trainUniformBooking = false;
        }
      }
      if (subsidyCtrl.dining && isProcessDining) {
        if (isDining) {
          this.travelParams.travelApplication.diningUniformBooking = true;
          this.travelParams.travelApplication.diningBookingClerkOID = this.props.form.getFieldValue('diningBookingClerkOID');
        } else {
          this.travelParams.travelApplication.diningUniformBooking = false;
        }
      }
      //订票平台相关的处理
      if (subsidyCtrl.flightPlatform) {
        this.travelParams.travelApplication.platformBookingClerkOID = this.props.form.getFieldValue('platformBookingClerkOID');
      }
      subsidyCtrl.isShowModal = false;
      this.setState({ subsidyCtrl: subsidyCtrl });
      this.executeTravelSubmit();
    }
  };

  //提交时加签人校验
  judgeSubmitSign = (params) => {
    let duplicateNameList = [];
    let duplicateOIDList = [];//去重逻辑
    let duplicateName = '';
    if (params.countersignApproverOIDs && params.countersignApproverOIDs.length && params.approvalHistorys && params.approvalHistorys.length) {
      params.approvalHistorys.map(history => {
        if (history.operation === 2001 && history.operator
          && params.countersignApproverOIDs.indexOf(history.operator.userOID) !== -1
          && history.operator.fullName && duplicateOIDList.indexOf(history.operator.userOID) === -1) {
          duplicateNameList.push(history.operator.fullName);
          duplicateOIDList.push(history.operator.userOID);
        }
      });
    }
    duplicateName = duplicateNameList.join(', ');
    return duplicateName;
  };

  //提交差旅申请单
  doRealExecuteTravelSubmit = (isIgnoreBudget, budgetCheckMessage, isIgnoreDateRepeat) => {
    //增加旧差旅行程
    if (this.state.travelItinerarys.length > 0) {
      this.travelParams.travelApplication.travelItinerarys = [];
      this.travelParams.travelApplication.travelItinerarys = this.state.travelItinerarys;
    }
    if (isIgnoreBudget) {
      //是否强制提交
      this.travelParams.ignoreBudgetWarningFlag = true;
      this.travelParams.budgetCheckMessage = budgetCheckMessage;
      this.setState({ submitLoading: true });
    }
    if (isIgnoreDateRepeat) {//#38375：日期重复若管控
      //日期重复时，是否强制提交
      this.travelParams.ignoreTimeWarningFlag = true;
      this.setState({ submitLoading: true });
    }
    travelService.submitTravelRequest(this.travelParams).then(res => {
      this.setState({ loading: false, submitLoading: false });
      if (!isIgnoreBudget && res.data && res.data.applicationDTO && ['BUD_002', 'BUD_003'].indexOf(res.data.applicationDTO.budgetLabelCode) > -1) {
        //弱管控
        if (res.data.applicationDTO.budgetLabelCode === 'BUD_003') {
          //弹框提示是否继续提交
          Modal.confirm({
            title: messages('request.key550')/*预算预警*/,
            content: <div>
              <p>{res.data.applicationDTO.budgetCheckMessage}</p>
            </div>,
            okText: messages('request.key180')/*继续提交*/,
            cancelText: messages('request.key194')/*返回修改*/,
            onOk: () => this.doRealExecuteTravelSubmit(true, res.data.applicationDTO.budgetCheckMessage),
            onCancel: () => this.pureCancelSubmit(res.data.applicationDTO)
          });
        }
        //强管控
        if (res.data.applicationDTO.budgetLabelCode === 'BUD_002') {
          //弹框提示超预算
          Modal.error({
            title: messages('request.key297')/*超预算*/,
            content: <div>
              <p>{res.data.applicationDTO.budgetCheckMessage}</p>
            </div>,
            okText: messages('request.key194')/*返回修改*/,
            onOk: () => this.pureCancelSubmit(res.data.applicationDTO)
          });
        }
      } else if (!isIgnoreDateRepeat) {//#38375：日期重复若管控
        const { checkResultList } = res.data;
        if (checkResultList[0] && checkResultList[0].externalPropertyName === '9003') {
          const errArr = checkResultList[0].message.split('﹤br/﹥') || [];
          //弹框提示是否继续提交
          Modal.confirm({
            title: messages('request.key682'/*出差往返日期重叠*/),
            content: <div>
              {errArr.map(e => (<p>{e}</p>))}
            </div>,
            okText: messages('request.key180')/*继续提交*/,
            cancelText: messages('request.key194')/*返回修改*/,
            onOk: () => this.doRealExecuteTravelSubmit(isIgnoreBudget, budgetCheckMessage, true),
            onCancel: () => this.pureCancelSubmit(),
            width: '800px'
          });
        } else {
          message.success(messages('request.key197'/*提交成功*/));
          this.goBack();
        }
      } else {
        message.success(messages('request.key197'/*提交成功*/));
        this.goBack();
      }
    }).catch(err => {
      this.setState({ loading: false, submitLoading: false });
      const errMsg = err.response.data.message || '';
      const errCode = err.response.data.errorCode;
      if (errCode === '11005' || errCode === '11004') {
        const errArr = errMsg.split('<br/>') || [];
        //弹框提示
        Modal.info({
          title: messages('request.key173'/*提示*/),
          content: <div>
            {errArr.map(e => (<p>{e}</p>))}
          </div>,
          okText: messages('common.ok')/*确认*/,
          width: '800px'
        });
      } else {
        message.error(messages('request.key190'/*操作失败:*/) + `${errMsg}`);
      }
    });
  };

  //执行差旅申请单提交接口
  executeTravelSubmit = () => {
    if (this.judgeSubmitSign(this.travelParams)) {
      //弹框提示是否继续提交
      Modal.confirm({
        title: messages('request.key173'/*提示*/),
        content: <div>
          <p>{messages('request.key458', { arg1: this.judgeSubmitSign(this.travelParams) }/*{arg1} 已审批通过，是否继续?*/)}</p>
        </div>,
        okText: messages('common.ok')/*删除*/,
        cancelText: messages('request.key175'/*取消*/),
        onOk: () => this.doExecuteTravelSubmit(),
        onCancel: () => this.pureCancelSubmit(),
      });
    } else {
      this.doExecuteTravelSubmit();
    }
  };

  doExecuteTravelSubmit = () => {
    //判断是否含有智能机票，如果含有，则需要额外校验人员信息
    if (this.state.itineraryData && this.state.itineraryData.AUTO_FLIGHT && this.state.itineraryData.AUTO_FLIGHT.length) {
      travelService.checkUserInfo(this.props.params.applicationOID).then(res => {
        if (res.data && res.data.length) {
          let content = messages('request.key536')/*当前出行人的人员信息中有为空项：*/;
          res.data.map(item => {
            let emptyData = [
              !item.withBirthday && messages('request.key537')/*生日*/,
              !item.withGender && messages('request.key538')/*性别*/,
              !item.withIdCard && messages('request.key539')/*身份证号*/,
              !item.withPhone && messages('request.key202')/*手机号*/
            ].filter(obj => obj);
            let userEmpty = `${!!emptyData.length && item.userName}:${emptyData.join('、')};`;
            content = `${content}${userEmpty}`;
          });
          Modal.info({
            title: messages('request.key173'/*提示*/),
            content: <div>
              <p>{content}</p>
            </div>,
            okText: messages('common.ok'),
            onOk: () => this.pureCancelSubmit()
          });
        } else {
          this.doExecuteTravelSubmitStepNext();
        }
      }).catch(err => {
        this.setState({ loading: false, submitLoading: false });
        message.error(messages('request.key190'/*操作失败:*/) + err.response.data.message);
      });
    } else {
      this.doExecuteTravelSubmitStepNext();
    }
  };

  //校验人员的护照信息
  doExecuteTravelSubmitStepNext = () => {
    const { itineraryData } = this.state;
    const { applicationOID } = this.props.params;
    if (false && itineraryData) { //task#42407：国际差旅申请单，添加国际行程后提醒无护照信息弹框隐藏
      travelService.checkUserInfoInter(applicationOID).then(res => {
        if (res.data && !res.data.success) {
          let nameList = [];
          let nameStr = '';
          res.data.data && res.data.data.map(user => {
            if (!user.withPassport) {
              nameList.push(user.userName);
            }
          });
          nameStr = nameList.join(' | ');
          this.setState({ userInfoCheckVisible: true, userCheckResult: nameStr });
        } else {
          this.doRealExecuteTravelSubmit();
        }
      }).catch(err => {
        this.setState({ loading: false, submitLoading: false });
        message.error(messages('request.key190'/*操作失败:*/) + err.response.data.message);
      });
    } else {
      this.doRealExecuteTravelSubmit();
    }
  };

  closeUserCheckModal = () => {
    this.setState({ userInfoCheckVisible: false });
    this.pureCancelSubmit();
  };

  //type 'save'仅保存 'submit'继续提交
  handleUserCheckModal = (type) => {
    this.setState({ userInfoCheckVisible: false });
    if (type === 'save') {
      this.cancelDelPartis(this.travelParams, 'save', 'edit');
    }
    if (type === 'submit') {
      this.doRealExecuteTravelSubmit();
    }
  };

  //统一订票modal阶段 取消提交返回界面
  cancelSubmit = () => {
    let subsidyCtrl = this.state.subsidyCtrl;
    subsidyCtrl.isShowModal = false;
    this.setState({
      subsidyCtrl: subsidyCtrl,
      loading: false,
      submitLoading: false,
    });
  };

  //applicationDTO 提交失败要刷新部分数据
  pureCancelSubmit = (applicationDTO) => {
    this.setState({ loading: false, submitLoading: false });
    if (applicationDTO) {
      this.processSubmitResult(applicationDTO);
    }
  };

  processSubmitResult = (applicationDTO) => {
    let warningList = applicationDTO.warningList ? JSON.parse(applicationDTO.warningList) : [];
    this.setState({ warningList });
    if (this.props.params.applicationOID) {
      //编辑直接提交，预算校验不通过
      //这里要区分费用申请单还是差旅申请单，两者预算明细处理不一样
      let isHasBudgetDetail = false;
      let budgetDetailValue = null;
      let id = 'formValueOID';
      let key = '';
      applicationDTO.custFormValues && applicationDTO.custFormValues.map(item => {
        if (item.messageKey === 'budget_detail') {
          isHasBudgetDetail = true;
          budgetDetailValue = item.value ? JSON.parse(item.value) : null;
          key = applicationDTO.formType === 2002 ? item[id] : 'travelBudgetDetail';
        }
      });
      if (isHasBudgetDetail && budgetDetailValue) {
        this.props.form.setFieldsValue({ [key]: budgetDetailValue });
      }
    } else {
      //新建直接提交，预算校验不通过
      //差旅申请单不能新建直接提交，所以这里只要处理费用申请单新建提交的情况即可
      this.props.params.applicationOID = applicationDTO.applicationOID;
      //提交接口的返回数据中applicationDTO.custFormValues里没有showValue，所以在新建费用单直接提交后，这里要重新调查详情接口
      this.setState({ loading: true });
      requestService.getRequestDetail(applicationDTO.applicationOID).then(res => {
        this.setState({ loading: false });
        let info = res.data;
        this.setApplicantDisable(info.custFormValues);
        info.custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
        info.custFormValues.map(item => {
          if (item.messageKey === 'select_participant' && item.value) {
            let arr = [];
            JSON.parse(item.value).map(detail => {
              let newItem = {
                userOID: detail.userOID,
                fullName: detail.fullName,
                participantOID: detail.participantOID
              };
              arr.push(newItem);
            });
            item.value = JSON.stringify(arr);
          }
        });
        this.copyDefaultCust({ data: info }, 'edit');
        this.setState({
          info,
          defaultValues: info.custFormValues
        });
      }).catch(e => {
        this.setState({ loading: false });
        let error = e.response.data;
        if (error.validationErrors && error.validationErrors.length) {
          message.error(error.validationErrors[0].message);
        } else {
          message.error(error.message);
        }
      });
    }
  };

  //是否统一订票开关
  onChangeSwitch = (type) => {
    let info = this.state.info;
    switch (type) {
      case 'flight':
        if (info.travelApplication.hasOwnProperty("uniformBooking")) {
          info.travelApplication.uniformBooking = !info.travelApplication.uniformBooking;
        }
        this.setState({ isFlight: !this.state.isFlight, info: info });
        break;
      case 'train':
        if (info.travelApplication.hasOwnProperty("trainUniformBooking")) {
          info.travelApplication.trainUniformBooking = !info.travelApplication.trainUniformBooking;
        }
        this.setState({ isTrain: !this.state.isTrain, info: info });
        break;
      case 'hotel':
        if (info.travelApplication.hasOwnProperty("hotelUniformBooking")) {
          info.travelApplication.hotelUniformBooking = !info.travelApplication.hotelUniformBooking;
        }
        this.setState({ isHotel: !this.state.isHotel, info: info });
        break;
      case 'dining':
        if (info.travelApplication.hasOwnProperty("diningUniformBooking")) {
          info.travelApplication.diningUniformBooking = !info.travelApplication.diningUniformBooking;
        }
        this.setState({ isDining: !this.state.isDining, info: info });

        break;
    }
  };

  //差旅申请单进入表头字段编辑状态
  goTravelEdit = () => {
    this.setState({ editTicketInfoVisible: false, participantChanged: false });
  };

  //编辑中的差旅申请单点击取消，退出表头字段编辑状态
  cancelTravelEdit = (custFormValues) => {
    let { info } = this.state;
    info.custFormValues = JSON.parse(JSON.stringify(custFormValues));
    this.setApplicantDisable(info.custFormValues);
    this.processTravelDate(info, 'edit');
    info.custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    info.custFormValues.map(item => {
      if (item.messageKey === 'select_participant' && item.value) {
        let arr = [];
        JSON.parse(item.value).map(detail => {
          let newItem = {
            userOID: detail.userOID,
            fullName: detail.fullName,
            participantOID: detail.participantOID
          };
          arr.push(newItem);
        });
        item.value = JSON.stringify(arr);
      }
    });
    this.copyDefaultCust({ data: info }, 'edit');
    this.setState({
      info: info,
      defaultValues: info.custFormValues,
      formIsChange: 'false',
      editTicketInfoVisible: true,
      isSaveBtnClicked: false
    });
  };

  //提交
  handleSubmit = () => {
    if (this.submitSaveValidateCombinationForm()) {
      this.setState({
        greenCodeAlertVisible: false,
      })
      //组合子表单验证信息传递需要时间
      setTimeout(this.delayHandleSubmit, 10);
    } else {
      this.delayHandleSubmit();
    }
  };
  //提交
  delayHandleSubmit = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log('values', values)
      if (!this.combinationFormValidateResult()) {
        return;
      }
      if (!err) {
        let params = this.props.params.applicationOID ? JSON.parse(JSON.stringify(this.state.info)) : JSON.parse(JSON.stringify(this.state.formInfo));
        // task#40495：机酒确认单审批驳回后不允许重新提交
        const { rejectType, formCode } = params;
        if ([1002, 1003, 1004].indexOf(rejectType) > -1 && ['OFFLINE_FLIGHT_CONFIRMATION_FORM', 'OFFLINE_HOTEL_CONFIRMATION_FORM'].indexOf(formCode) > -1) {
          Modal.confirm({
            title: messages('request.key173'/*提示*/),
            content: messages('mcd.offline.reject'/*该单据已被驳回，无法提交*/),
            okText: messages('common.ok')/*确认*/,
            cancelText: messages('request.key175'/*取消*/)
          });
          return;
        }
        params.custFormValues = this.getCustFormValues(values, true);
        if (this.state.formType === 2001) {
          this.processBeforeSaveOrSubmit(params.custFormValues);
        }
        this.processApportionment(params.custFormValues);
        if (!this.custFormValuesValidate(params.custFormValues)) {
          return;
        }
        params.referenceApplicationOID = this.state.referenceApplicationOID;
        const { loginUser } = this.props;
        if (this.props.form.getFieldsValue().addSign) {
          const addSignVal = this.props.form.getFieldsValue().addSign;
          const TMCFiled = params.custFormValues.filter(item => item.fieldCode === 'TMC');
          let TMCVal;
          if (TMCFiled && TMCFiled.length && TMCFiled[0]) {
            TMCVal = TMCFiled[0].value;
          }
          params.countersignApproverOIDs = (typeof addSignVal === 'string') ? [addSignVal] : addSignVal;
          const uID = loginUser.userOID;
          if (TMCVal === '2' && ['MCD3001', 'OFFLINE_HOTEL_CONFIRMATION_FORM', 'OFFLINE_FLIGHT_CONFIRMATION_FORM'].indexOf(formCode) > -1 && params.countersignApproverOIDs[0] !== uID) {
            params.countersignApproverOIDs.unshift(uID);
          }
        }
        if (['SQ017','SQ018'].includes(params.formCode)) {
          params.proxyApplyScope = params.custFormValues[6].value ? 1 : 0;
        }
        this.processValues(params);
        this.handleSubmitStep1(params);
      }
    });
  };

  handleSubmitStep1 = (params) => {
    const { formType } = this.state;    //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
    this.setState({ submitLoading: true });
    if (formType === 2001 || formType === 2002) {//wjk add 18 04 16 差旅提交分支
      //提交校验预算上的默认分摊是否和表单上的部门，成本中心控件一致
      if (this.checkApportion(params.custFormValues)) {
        //弹框提示是否继续提交
        Modal.confirm({
          title: messages('request.key173'/*提示*/),
          content: <div>
            <p>{messages('request.key533')/*默认分摊与表头的值不一致，是否继续提交？*/}</p>
          </div>,
          okText: messages('common.ok')/*确认*/,
          cancelText: messages('request.key175'/*取消*/),
          onOk: () => {
            if (formType === 2001) {
              this.isHaveRepeatSubsidy(params, 'submit');
            }
            if (formType === 2002) {
              this.handleSubmitStep2(params);
            }
          },
          onCancel: () => this.pureCancelSubmit(),
        });
      } else {
        //wjk add 20180725 提交时判断差补明细是否有重复
        if (formType === 2001) {
          this.isHaveRepeatSubsidy(params, 'submit');
        }
        if (formType === 2002) {
          this.handleSubmitStep2(params);
        }
      }
      return;
    }
    this.handleSubmitStep2(params);
  };

  //除开差旅单的提交
  handleSubmitStep2 = (params) => {
    if (this.judgeSubmitSign(params)) {
      //弹框提示是否继续提交
      Modal.confirm({
        title: messages('request.key173'/*提示*/),
        content: <div>
          <p>{messages('request.key458', { arg1: this.judgeSubmitSign(params) }/*{arg1} 已审批通过，是否继续?*/)}</p>
        </div>,
        okText: messages('common.ok')/*删除*/,
        cancelText: messages('request.key175'/*取消*/),
        onOk: () => this.doExecuteOtherSubmit(params),
        onCancel: () => this.pureCancelSubmit(),
      });
    } else {
      this.doExecuteOtherSubmit(params);
    }
  };

  //非差旅单的提交
  doExecuteOtherSubmit = (params, isIgnoreBudget, isIgnoreDateRepeat) => {
    let formType = this.state.formType;    //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
    if (isIgnoreBudget) {
      //是否强制提交
      params.ignoreBudgetWarningFlag = true;
      this.setState({ submitLoading: true });
    }
    if (isIgnoreBudget) {//#38375：日期重复若管控
      params.ignoreTimeWarningFlag = true;
      this.setState({ submitLoading: true });
    }
    let getType =
      formType === 2001 ? '' :
        formType === 2002 ? 'submitExpenseRequest' :
          formType === 2003 ? 'submitBookerRequest' :
            formType === 2004 ? '' : 'submitLoanRequest';
     console.log('params', params)
    let hasTrue = false;
    if (getType === 'submitExpenseRequest' && params.formCode === 'SQ001') {
      let numData = params.custFormValues.filter(e => {
        return e.fieldName === '商务应酬人数'
      });
      let listData = params.custFormValues.filter(e => {
        return e.fieldName === '参与人清单'
      });
      // console.log('numData', numData)
      // console.log('listData', listData)
      if (Number(numData[0].value) <= 10) {
        // console.log(listData[0].value.split('},{').length)
        let listNum = listData[0].value.split('},{').length;
        if (listNum !== Number(numData[0].value)) {
          // message.warning('申请单人数和列表中的数量不一致，请修改');
          // hasTrue = false;
          // this.setState({ submitLoading: false });
          hasTrue = true;
        } else {
          hasTrue = true;
        }
      } else {
        let listNum = listData[0].value.split('},{').length;
        if (listNum < 10) {
          message.warning('请在列表中添加至少10个商务应酬人员');
          hasTrue = false;
          this.setState({ submitLoading: false });
        } else {
          hasTrue = true;
        }
      }
    } else {
      hasTrue = true;
    }
    if (hasTrue) {
      // if (['SQ018'].includes(params.formCode)) {
      //   params.costCenterItemOID = params.custFormValues[1].value;
      // }
      // https://pmo.mcd.com.cn/jira/browse/TES-2285
      if (this.state.formInfo.formCode === 'SQ008') {
        params.giftApplyBill = getGiftDeclareValue({}, this);
      }
      console.log('params', params)
      requestService[getType](params).then(res => {
        /**
         * 如果是礼品申报单，再保存礼品申报单详情
         */
        if(this.state.formInfo.formCode === 'SQ008') {
          return giftDeclareService.saveGiftDeclare(getGiftDeclareValue(res.data.applicationDTO, this), !!this.state.info.businessCode).then(res2 => {
            return res
          })
        } else {
          return res
        }
      }).then((res) => {
        //提交前检查附件是否为空
        // if(this.state.formInfo.formCode === "SQ008"){
        //   if(!this.checkFileUpload(res.data, this)){
        //     return ;
        //   }
        // }
        this.setState({ submitLoading: false });
        if (!isIgnoreBudget && formType === 2002 && res.data && res.data.applicationDTO && ['BUD_002', 'BUD_003'].indexOf(res.data.applicationDTO.budgetLabelCode) > -1) {
          //弱管控
          if (res.data.applicationDTO.budgetLabelCode === 'BUD_003') {
            //弹框提示是否继续提交
            Modal.confirm({
              title: messages('request.key550')/*预算预警*/,
              content: <div>
                <p>{res.data.applicationDTO.budgetCheckMessage}</p>
              </div>,
              okText: messages('request.key180')/*继续提交*/,
              cancelText: messages('request.key194')/*返回修改*/,
              onOk: () => this.doExecuteOtherSubmit(res.data.applicationDTO, true),
              onCancel: () => this.pureCancelSubmit(res.data.applicationDTO)
            });
          }
          //强管控
          if (res.data.applicationDTO.budgetLabelCode === 'BUD_002') {
            //弹框提示超预算
            Modal.error({
              title: messages('request.key297')/*超预算*/,
              content: <div>
                <p>{res.data.applicationDTO.budgetCheckMessage}</p>
              </div>,
              okText: messages('request.key194')/*返回修改*/,
              onOk: () => this.pureCancelSubmit(res.data.applicationDTO)
            });
          }
        } else if(this.state.formInfo.formCode === 'SQ024'){
          message.success(messages('common.operate.success'));

          // 如果非代理人申请则退出登陆
          if(this.state.principalOID){
            this.goBack();
          }else {
            //清空documentaryCompany的redux信息
            configureStore.store.dispatch(setDocumentaryCompany({}));
            // 有了单点登录之后
            mainService.loginOutSso()
              .then((res) => {
                removeToken("language");
                this.context.router.push('/?logout_sso=true');
              })
          }

        } else if (!isIgnoreDateRepeat) {//#38375：日期重复若管控
          const { checkResultList } = res.data;
          if (checkResultList[0] && checkResultList[0].externalPropertyName === '9003') {
            const errArr = checkResultList[0].message.split('﹤br/﹥') || [];
            //弹框提示是否继续提交
            Modal.confirm({
              title: messages('request.key682'/*出差往返日期重叠*/),
              content: <div>
                {errArr.map(e => (<p>{e}</p>))}
              </div>,
              okText: messages('request.key180')/*继续提交*/,
              cancelText: messages('request.key194')/*返回修改*/,
              onOk: () => this.doExecuteOtherSubmit(params, isIgnoreBudget, true),
              onCancel: () => this.pureCancelSubmit(),
              width: '800px'
            });
          } else {
            message.success(messages('common.operate.success'));
            this.goBack();
          }
        }  else {
          message.success(messages('common.operate.success'));
          this.goBack();
        }
      }).catch(e => {
        this.setState({ submitLoading: false });
        if (this.submitError(e)) {
          return;
        }
        errorMessage(e.response);
      });
    }
  };
  submitError = (e) => {
    let data = e.response.data;
    if (data && data.errorCode === '6017007') {
      Modal.warning({
        title: messages('request.key569')/*您的免费试用已经到期，请联系汇联易*/,
        content: '400 829 7878',
      });
      return true;
    }
  };
  /**
   * 根据差补总额，更新总金额
   * @param total number 差补总额
   * @param isClear Boolean 是否清空差补
   * @param isRoute Boolean 是否有行程存在
   * @param isRepeatSubsidy Boolean 是否有重复差补明细
   * @param itineraryData obj 行程信息
   * @param isRefreshBudget Boolean 是否需要刷新预算明细
   */
  updateTotalBudget = (total, isClear, isRoute, isRepeatSubsidy, itineraryData, isRefreshBudget) => {
    this.setState({
      total: total,
      haveClear: isClear,
      isFirstSave: false,
      totalBudget: this.state.amount + total,
      isHaveRoute: isRoute,
      itineraryData: itineraryData,
      isRepeatSubsidy: isRepeatSubsidy ? true : false
    })
    if (isRefreshBudget) {
      this.refreshBudget();
    }
  };

  //刷新预算明细
  refreshBudget = (callback) => {
    const { travelBudgetDetailObj, formInfo, editTicketInfoVisible } = this.state;
    const { applicationOID } = this.props.params;
    const { setFieldsValue } = this.props.form;
    if (formInfo.customFormPropertyMap
      && formInfo.customFormPropertyMap['itinerary.auto.budget2']
      && JSON.parse(formInfo.customFormPropertyMap['itinerary.auto.budget2']).enabled) {
      requestService.getApplicationBudgetList(applicationOID).then(res => {
        if (res.data && res.data.value) {
          let editBudgetList = travelBudgetDetailObj ? travelBudgetDetailObj.budgetDetail : [];
          let newBudgetList = JSON.parse(res.data.value).budgetDetail;
          let deletedBudgetOIDList = (travelBudgetDetailObj && travelBudgetDetailObj.deletedBudgetOIDList) ? travelBudgetDetailObj.deletedBudgetOIDList : [];
          let resultBudgetList = travelUtil.calculateBudget(editBudgetList, newBudgetList, deletedBudgetOIDList);
          let resultValue = {
            deletedBudgetOIDList,
            amount: 0, //这个金额在预算明细控件中会重算的，此处置0即可
            refreshAmount: !!resultBudgetList.length, //标记重算金额，同时会把开了分摊但是没有默认分摊的费用加上默认分摊
            budgetDetail: resultBudgetList
          };
          if (editTicketInfoVisible) {
            setFieldsValue({ "travelBudgetDetail": resultValue });
          } else {
            //修改日期，参与人清空差补，此时没有fieldValue为travelBudgetDetail
            this.setState({ travelBudgetDetailObj: JSON.parse(JSON.stringify(resultValue)) });
          }
        }
        callback && callback();
      }).catch(e => {
        callback && this.setState({ loading: false, saveLoading: false })
        message.error(e.response.data.message);
      });
    }
  };

  beforeAddSubsidyToSave = (boo) => {
    if (boo) {
      this.isSubsidySave = true;
      this.handleSave();
    }
  }

  //删除
  handleDelete = () => {
    this.setState({ deleteLoading: true });
    if (this.state.formInfo.formCode === 'SQ008') {
      // 删除申报单
      giftDeclareService.delGiftDeclare({ businessCode: this.state.info.businessCode }).catch(e => {
        errorMessage(e.response);
      })
    }
    requestService.deleteRequest(this.props.params.applicationOID).then(res => {
      this.setState({ deleteLoading: false });
      message.success(messages('common.delete.success', { name: '' }));
      this.goBack()
    }).catch(e => {
      this.setState({ deleteLoading: false });
      errorMessage(e.response);
    })
  };
  //返回
  goBack = () => {
    this.setState({ participantChanged: false });
    menuRoute.goBack(this)
  };
  formItemChange(value) {
    let { formInfo, defaultValues } = this.state;
    let custForm = this.props.params.applicationOID ? defaultValues || [] : formInfo.customFormFields || [];
    let id = this.props.params.applicationOID ? 'formValueOID' : 'fieldOID';
    custForm.map(item => {
      //参与人部门权限控件
      //差旅单参与人权限校验不走这里，在提交处校验
      if ((item.messageKey === 'select_department' || item.messageKey === 'select_cost_center') && value && Object.prototype.toString.call(value) === '[object Object]' && item[id] in value && this.state.formType !== 2001) {
        item.value = value[item[id]];
        custForm.map(i => {
          if (i.messageKey === 'select_participant') {
            setTimeout(() => {
              firstInitLoad = true;
            }, 200);
            if (firstInitLoad) {
              i.clearDefault = true;
            }
            let fieldContent = i.fieldContent ? JSON.parse(i.fieldContent) : { editable: true };
            let isUse = true;
            if (fieldContent.isUse === false) {
              isUse = false;
            }
            if (!i.isReadOnly && fieldContent.editable && isUse) {
              this.props.form.resetFields(i[id]);
            }
          }
        });
      }
      //收款人银行关联控件
      if (item.messageKey === 'payee' && value && Object.prototype.toString.call(value) === '[object Object]' && item.fieldOID in value && value[item.fieldOID] && typeof value[item.fieldOID] == 'object') {
        item.value = value[item.fieldOID]['key'];
        custForm.map(i => {
          if (i.messageKey === 'contact_bank_account') {
            let param = {
              userOID: value[item.fieldOID]['key'],
              page: 0,
              size: 20
            };
            let bank = {
              [i.fieldOID]: [{
                bankAccountNo: null,
                originalBankAccountNo: null,
                contactBankAccountOID: null
              }]
            };
            baseService.getUserBanks(param).then(res => {
              let data = res.data;
              if (data && data.length > 0) {
                data.map(item => {
                  if (item.isPrimary) {
                    bank = {
                      [i.fieldOID]: [{
                        bankAccountNo: item.bankAccountNo,
                        originalBankAccountNo: item.originalBankAccountNo,
                        contactBankAccountOID: item.contactBankAccountOID
                      }]
                    };
                  }
                })
              }
              this.props.form.setFieldsValue(bank);
            }).catch(e => {
              this.props.form.setFieldsValue(bank);
            })
          }
        });
      }
    })
  }

  createHotelPeople = () => {
    this.setState({ randomHotel: true });
    travelService.randomCreateHotelPeople(this.state.maxHotel).then(res => {
      this.props.form.setFieldsValue({ 'travelHotelBookingMaleClerks': res.data.maleUserOIDs });
      this.props.form.setFieldsValue({ 'travelHotelBookingFemaleClerks': res.data.femaleUserOIDs });
      this.setState({ randomHotel: false });
    }).catch(err => {
      message.error(err.response.data.message);
      this.setState({ randomHotel: false });
    })
  }

  //去借款
  goAutoLoan = () => {
    //1.判断预算明细个人支付金额是否大于0
    const { formType, formInfo, defaultValues, travelBudgetDetailObj, info, jobId } = this.state;
    const { applicationOID } = this.props.params;
    let custForm = applicationOID ? defaultValues || [] : formInfo.customFormFields || [];
    let loanFormOID = '';
    if (formInfo.customFormPropertyMap && formInfo.customFormPropertyMap["application.direct.loan.type"]) {
      loanFormOID = formInfo.customFormPropertyMap["application.direct.loan.type"];
    }
    let budgetDetail = [];
    let isHasPersonalAmount = false; //个人支付金额是否大于0
    let businessCode = info && info.loanBillOID && info.loanBill.businessCode;
    let loanStatus = info && info.loanBill && info.loanBill.status;
    if (loanStatus === 1010) {
      message.error(messages('request.key570')/*未找到借款单，单据可能已被删除。*/);
      return;
    }
    this.setState({ autoLoanLoading: true });
    if (formType === 2001 && travelBudgetDetailObj && travelBudgetDetailObj.budgetDetail && travelBudgetDetailObj.budgetDetail.length) {
      travelBudgetDetailObj.budgetDetail.map(budget => {
        if (budget.paymentType == 1001) {
          isHasPersonalAmount = true;
        }
      });
    }
    if (formType === 2002) {
      custForm.map(i => {
        if (i.messageKey === 'budget_detail' && i.value && JSON.parse(i.value)
          && JSON.parse(i.value).budgetDetail && JSON.parse(i.value).budgetDetail.length) {
          budgetDetail = JSON.parse(i.value).budgetDetail;
        }
      });
    }
    budgetDetail.length && budgetDetail.map(budget => {
      if (budget.paymentType == 1001) {
        isHasPersonalAmount = true;
      }
    });
    if (isHasPersonalAmount) {
      if (!businessCode) {
        //2.校验是否有权限创建借款单
        let applicantOID = this.getApplicantOID();
        requestService.checkAutoLoan(applicantOID, loanFormOID, jobId).then(res => {
          //3.正常的保存申请单的流程
          this.setState({ autoLoanLoading: false });
          this.handleSave(true);
        }).catch(err => {
          if (err.response && err.response.data) {
            message.error(err.response.data.validationErrors ? err.response.data.validationErrors[0].message : err.response.data.message);
          }
          this.setState({ autoLoanLoading: false });
        });
      } else {
        //如果是已存在创建的关联借款单，直接走保存接口，不用再调查询权限接口
        this.setState({ autoLoanLoading: false });
        this.handleSave(true);
      }
    } else {
      message.error(messages('request.key567')/*个人支付金额需大于0*/);
      this.setState({ autoLoanLoading: false });
    }
  };

  goCreateLoan = (applicationOID) => {
    const { formInfo, info, jobId } = this.state;
    let loanFormOID = '';
    let url = '';
    let loanBillOID = info && info.loanBillOID;
    let loanFormType = info && info.loanBill && info.loanBill.type;
    if (formInfo.customFormPropertyMap && formInfo.customFormPropertyMap["application.direct.loan.type"]) {
      loanFormOID = formInfo.customFormPropertyMap["application.direct.loan.type"];
    }
    if (info && info.loanBillOID && info.loanBill.formOID) {
      loanFormOID = info.loanBill.formOID;
    }
    if (loanBillOID) {
      if (loanFormType === 2005) {
        //单行借款单编辑页
        url = this.editLoan.url.replace(':formOID', loanFormOID).replace(':loanBillOID', loanBillOID).replace(':applicationOID', applicationOID);
      } else {
        //多行借款单编辑页
        url = this.loanDetail.url.replace(':formOID', loanFormOID).replace(':loanBillOID', loanBillOID).replace(':applicationOID', applicationOID);
      }
    } else {
      url = this.newLoan.url.replace(':formOID', loanFormOID).replace(':applicationOID', applicationOID).replace(':jobId', jobId);
    }
    this.context.router.push(url);
  };

  getApplicantOID = () => {
    const { info } = this.state;
    const { applicationOID, applicantOID } = this.props.params;
    const { userOID } = this.props.user;
    let resultApplicantOID = '';
    if (applicationOID) {
      resultApplicantOID = info.applicant && info.applicant.userOID;
    } else {
      resultApplicantOID = (applicantOID && applicantOID !== ':applicantOID') ? applicantOID : userOID;
    }
    return resultApplicantOID;
  };

  renderAutoLoan = () => {
    const { autoLoanLoading, info } = this.state;
    let currencyCode = info && info.loanBillOID && info.loanBill.currencyCode;
    let currencyAmount = info && info.loanBillOID && info.loanBill.currencyAmount;
    let businessCode = info && info.loanBillOID && info.loanBill.businessCode;
    return (
      <div>
        {!autoLoanLoading && (
          <span>
            {info && info.loanBillOID && (
              <span style={{ fontSize: '16px', color: '#000000', fontWeight: '700' }}>
                {currencyCode}&nbsp;{React.Component.prototype.filterMoney(currencyAmount, queryCurrencyPrecision(currencyCode), true)}&nbsp;&nbsp;&nbsp;
              </span>
            )}
            <span onClick={this.goAutoLoan} className='default-color-font' style={{ cursor: 'pointer' }}>
              {businessCode}{!businessCode && <span>{messages('request.key568')/*去借款*/}</span>}&nbsp;<Icon type="right" />
            </span>
          </span>
        )}
        {autoLoanLoading && <Icon type="loading" />}
      </div>
    )
  };
  //代理审批人发生改变
  onApproverChange = (field, all, from) =>{
    const { userOID } = this.props.user;
    const copy = deepFullCopy(this.state)
    let applicantOID = this.props.params.applicantOID && this.props.params.applicantOID.indexOf('applicantOID') == 1 ? true : false;
    console.log("all", all, from)
    let dataList = applicantOID ? copy.formDate : copy.copyDefaultValues;
    // console.log('this.props.form', this.props.form.getFieldsValue())
    if(['SQ019'].includes(copy.formInfo.formCode) && all && all.employeeID){
      requestService.getDirverCarNumber(all.employeeID).then(res => {
        if (res.data && res.data.length === 1) {
          let dirverData = res.data[0];
          dataList.map(item => {
            let obj = {};
            if(item.fieldCode === "carIID"){
              if (applicantOID) {
                obj[item.fieldOID] = [{ carNumber: dirverData.carNumber, id: dirverData.id }];
              } else {
                obj[item.formValueOID] = [{ carNumber: dirverData.carNumber, id: dirverData.id }];
              }
              this.setState({ thirdUserEid: all.employeeID })
              this.props.form.setFieldsValue(obj)
            }
          })
        } else if (res.data.length > 1) {
          dataList.map(item => {
            let obj = {};
            if(item.fieldCode === "carIID"){
              if (applicantOID) {
                obj[item.fieldOID] = null;
              } else {
                obj[item.formValueOID] = null;
              }
              this.setState({ thirdUserEid: all.employeeID })
              this.props.form.setFieldsValue(obj)
            }
          })
          // message.warning('该司机设置了两个车牌号，请联系管理员处理')
        }
      }).catch(err => {
        message.error(err.message);
        this.setState({ thirdUserEid: all.employeeID });
      })
    }
    if(['SQ019'].includes(copy.formInfo.formCode) && all && all.vnlgnm && from){
      requestService.getProxyRuleHint(all.vnvndr, userOID, copy.formInfo.formCode).then(res => {
        console.log("res", res)
        if (res.data && res.data.length > 0) {
          Modal.info({
            title: '提示',
            content: (
              <div>
                {res.data.map((data, index) => (
                  <p key={index}>{index + 1}.{data}</p>
                ))}
              </div>
            ),
            onOk() {},
          });
        }
      })
    }
    if (['SQ018'].includes(copy.formInfo.formCode)) {
        dataList.map(item =>{
          if(item.fieldCode === 'AuthorizedRank'){
            let obj = {};
            if (applicantOID) {
              obj[item.fieldOID] = all.rank;
            } else {
              obj[item.formValueOID] = all.rank;
            }
            this.props.form.setFieldsValue(obj)
          }
          // console.log('this.props.form', this.props.form.getFieldsValue())
          if(item.messageKey === "select_user"){
            console.log('this.state', this.state)
            if (from && from === 'handleListOk') {
              requestService.getProxyRuleHint(all.userOID, userOID, copy.formInfo.formCode).then(res => {
                console.log("res", res)
                if (res.data && res.data.length > 0) {
                  Modal.info({
                    title: '提示',
                    content: (
                      <div>
                        {res.data.map((data, index) => (
                          <p key={index}>{index + 1}.{data}</p>
                        ))}
                      </div>
                    ),
                    onOk() {},
                  });
                }
              })
            }
            this.setState({ principalOID: all.userOID })
          }
        })
    }
    if (['SQ017'].includes(copy.formInfo.formCode)) {
        dataList.map(item =>{
          if(item.messageKey === "select_user"){
            if (from && from === 'handleListOk') {
              requestService.getProxyRuleHint(all.userOID, userOID, copy.formInfo.formCode).then(res => {
                console.log("res", res)
                if (res.data && res.data.length > 0) {
                  Modal.info({
                    title: '提示',
                    content: (
                      <div>
                        {res.data.map((data, index) => (
                          <p key={index}>{index + 1}.{data}</p>
                        ))}
                      </div>
                    ),
                    onOk() {},
                  });
                }
              })
            }
            this.setState({ principalOID: all.userOID })
          }
        })
    }
    if (['SQ007'].includes(copy.formInfo.formCode)) {
      dataList.map(item =>{
        let obj = {};
        if(item.fieldName === '公务卡归属人EID' && all.eid){
          if (applicantOID) {
            obj[item.fieldOID] = all.eid;
          } else {
            obj[item.formValueOID] = all.eid;
          }
          this.props.form.setFieldsValue(obj)
        }
        if(item.fieldName === '公务卡完整卡号'){
          if (applicantOID) {
            obj[item.fieldOID] = undefined;
          } else {
            obj[item.formValueOID] = undefined;
          }
          this.props.form.setFieldsValue(obj)
        }
        if(item.fieldName === '员工所属公司' && all.companyName){
          if (applicantOID) {
            obj[item.fieldOID] = { key: all.companyName, label: all.companyOID, companyOID: all.companyOID };
          } else {
            obj[item.formValueOID] = { key: all.companyName, label: all.companyOID, companyOID: all.companyOID };
          }
          this.props.form.setFieldsValue(obj)
        }
        if(item.fieldName === '员工所属部门' && all.departmentName){
          if (applicantOID) {
            obj[item.fieldOID] = [{ name: all.departmentName, costCenterItemOID: all.departmentOID }];
            // obj[item.fieldOID] = all.departmentOID;
          } else {
            obj[item.formValueOID] = [{ name: all.departmentName, costCenterItemOID: all.departmentOID }];
            // obj[item.formValueOID] = all.departmentOID;
          }
          this.props.form.setFieldsValue(obj)
        }
      })
    }
  }
  //代理全部开关打开
  onAgentChange = (field) =>{
    //代理申请需要处理
    const copy = deepFullCopy(this.state)
    console.log('copy', this.props.form.getFieldsValue(), field)
    if (!copy.principalOID && ['SQ017','SQ018'].includes(copy.formInfo.formCode)) {
      message.warning('请先选择授权人');
    } else {
      if(['SQ017','SQ018'].includes(copy.formInfo.formCode)){
        if(field){
          // 申请单参数
          let params1001 = {
            customFormType: 1001,
            operationCode:  1,
            principalOID: copy.principalOID,
            proxyOID: copy.jobInfo.userOID
          };
          // 报销单参数
          let params1002 = {
            customFormType: 1002,
            operationCode:  1,
            principalOID: copy.principalOID,
            proxyOID: copy.jobInfo.userOID
          };
          // 借款单参数
          let params3001 = {
            customFormType: 3001,
            operationCode:  1,
            principalOID: copy.principalOID,
            proxyOID: copy.jobInfo.userOID
          };
          Promise.all([
            requestService.getFormsProxy(params1002),
            requestService.getFormsProxy(params1001),
            requestService.getFormsProxy(params3001),
          ]).then(res => {
            let applyData = res[1].data;
            let expenseData = res[0].data;
            let loanData = res[2].data;
            let expenseNameList = [];
            let applyNameList = [];
            let loanNameList = [];
            expenseData && expenseData.length && expenseData.map(e => {
              expenseNameList.push({
                formOID: e.formOID,
                formName: e.formName
              })
            });
            applyData && applyData.length && applyData.map(e => {
              applyNameList.push({
                formOID: e.formOID,
                formName: e.formName
              })
            });
            loanData && loanData.length && loanData.map(e => {
              loanNameList.push({
                formOID: e.formOID,
                formName: e.formName
              })
            });
            let { formInfo } = copy;
            formInfo.customFormFields.map((item,index) =>{
              if(item.messageKey === "cust_list"){
                let obj = {};
                let applicantOID = this.props.params.applicantOID && this.props.params.applicantOID.indexOf('applicantOID') == 1 ? true : false;
                if (item.fieldCode === 'SQ') {
                  if (applicantOID) {
                    obj[item.fieldOID] = applyData;
                  } else {
                    obj[item.formValueOID] = applyData;
                  }
                } else if (item.fieldCode === 'BX') {
                  if (applicantOID) {
                    obj[item.fieldOID] = expenseData;
                  } else {
                    obj[item.formValueOID] = expenseData;
                  }
                } else if (item.fieldCode === 'JK') {
                  if (applicantOID) {
                    obj[item.fieldOID] = loanData;
                  } else {
                    obj[item.formValueOID] = loanData;
                  }
                } else {
                  if (applicantOID) {
                    obj[item.fieldOID] = [];
                  } else {
                    obj[item.formValueOID] = [];
                  }
                }
                item.isReadOnly = true;
                this.props.form.setFieldsValue(obj)
                this.updateCopyDefaultValue(index,item)
              }
            })
            this.setState({ formInfo, proxyApplyScope: 1, isCustListSwitch: true })
            this.props.params.proxyApplyScope = 1
          })
        }else{
          let { formInfo } = copy;
          formInfo.customFormFields.map((item,index) =>{
            if(item.messageKey === "cust_list"){
              let obj = {};
              let applicantOID = this.props.params.applicantOID && this.props.params.applicantOID.indexOf('applicantOID') == 1 ? true : false;
              if (applicantOID) {
                obj[item.fieldOID] = [];
              } else {
                obj[item.formValueOID] = [];
              }
              item.isReadOnly = false;
              this.props.form.setFieldsValue(obj)
              this.updateCopyDefaultValue(index,item)
            }
          })
          this.setState({ formInfo, proxyApplyScope: 0, isCustListSwitch: false })
          this.props.params.proxyApplyScope = 0
        }
      }
    }
  }

  // 当“是否显示关联”组件的switch的状态发生变化时触发
  // TODO heineiuo
  onSwitchChange = (field, checked) => {
    const { form } = this.props;
    const map = item => {
      if (item.fieldOID === field.fieldOID) {
        return {
          ...item,
          isSwitchOn
        }
      }
      return item
    }

    this.setState({
      info: {
        ...this.state.info,
        custFormValues:
          (this.state.info.custFormValues||[]).map(map)
      },
      formInfo: {
        ...this.state.formInfo,
        customFormFields:
          (this.state.formInfo.customFormFields||[]).map(map)
      }
    }, () =>{
      form.validateFields([field.fieldOID], { force: true });
    })
  }

  onProxy = (field, e, all) => {
    console.log('field', field, all)
    if (field.fieldCode === "carIID") {
      let obj = {};
      let value = {
        id: all.id,
        cardNumber: all.cardNumber
      };
      obj[field.fieldOID] = JSON.stringify(e);
      this.props.form.setFieldsValue(obj);
    } else {
      let obj = {};
      obj[field.fieldOID] = JSON.stringify(e);
      this.props.form.setFieldsValue(obj);
    }
    // console.log('e', field, JSON.stringify(e), all, this.props.form.getFieldsValue())
  }

  //  获取代第三方报销单据类型
  getThirdType = () => {
    console.log('thsaaaaaaaaaa a aaaaaaaaa', this.state)
    const { formInfo } = this.state;
    formInfo.customFormFields.map(item => {
      if (item.fieldName === '代第三方报销单据类型') {
        let customEnumerationOID = JSON.parse(item.dataSource).customEnumerationOID;
        let applicantOID = this.getApplicantOID();
        requestService.getThirdTypeList(customEnumerationOID, applicantOID).then(res => {
          let isApplicantOID = this.props.params.applicantOID && this.props.params.applicantOID.indexOf('applicantOID') == 1 ? true : false;
          let dataList = isApplicantOID ? this.state.formDate : this.state.copyDefaultValues;
          console.log('getThirdTypeList=======', dataList)
          if (res.data) {
            dataList.map(data => {
              if (data.fieldName === '代第三方报销单据类型') {
                let obj = {};
                if (applicantOID) {
                  obj[item.fieldOID] = [{ messageKey: res.data[0].messageKey, value: res.data[0].value }];
                } else {
                  obj[item.formValueOID] = [{ messageKey: res.data[0].messageKey, value: res.data[0].value }];
                }
                this.props.form.setFieldsValue(obj)
              }
            })
          }
        })
      }
    })
  }

  render() {
    const { isPreVersion } = this.props.location.query;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const { params, loginUser } = this.props;
    const { subsidyCtrl, loading, formInfo, formDefaultValue, defaultValues, saveLoading, deleteLoading, submitLoading,
      approvalHistory, signEnable, signReset, participantChanged, isShowRangePicker, travelItinerarys, dateChage, signCompanyOIDs, maxHotel, randomHotel,
      copyDefaultValues, isFlight, isTrain, isHotel, info, formType, total, amount, totalBudget, percent, budgeting,
      haveClear, formIsChange, currentCodeType, editTicketInfoVisible, tabKey, valuesOnlyForShow, travelBudgetDetailObj,
      isHasTravelBudgetDetail, warningList, travelElementServiceName, userInfoCheckVisible, userCheckResult, isProxy,
      budgetExplainNumber, isFirstSave, jobId, jobInfo, thirdPartyInfo, isFlightSwitch, isTrainSwitch, isHotelSwitch,
      isDiningSwitch, isSaveBtnClicked, originalFormInfo, isHR, isCustListSwitch, userIsHr, hrInfo, thirdUserEid,showSubmitBtn,fafangleixingFlag
    } = this.state;
    console.log('thirdUserEid', thirdUserEid)
    let thirdUserEidValue = thirdUserEid;
    const { formCode } = formInfo;
    const { formCodes } = config;
    let customFormFields = formInfo.customFormFields || [];
    if(formCode == "SQ002"){
      customFormFields = customFormFields.filter(i=>i.fieldCode != 'luojipanduan')
    }

    // customFormFields.sort((a, b) => a.sequence > b.sequence || -1);//wjk 注释
    // defaultValues.sort((a, b) => a.sequence > b.sequence || -1);//wjk 注释，初始化地方排序了
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    const formItemLayoutModal = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14, offset: 1 },
    };
    let additionalDefault = [loginUser.userOID];
    // let signPerson = params.applicationOID ? [] : [{userOID: loginUser.userOID, fullName: loginUser.fullName}];
    let signPerson = [];
    info.countersignApproverNames && info.countersignApproverNames.map(item => {
      // task#40915：团体申请单，草稿页面点击编辑后，保留原自选审批人 -- 字段只展示审批人
      if (item.userOID !== loginUser.userOID) {
        signPerson.push({ userOID: item.userOID, fullName: item.fullName })
      }
    });
    // 处理warningList中的换行
    let ind;
    warningList && warningList.map((w, index) => {
      w.externalPropertyName === '9003' && (ind = index); // 非审批审核的单据，隐藏日期重复标签
    });
    warningList[ind] && warningList.splice(ind, 1);

    // 参与人改变时，重置自选审批人
    if (participantChanged) {
      // signPerson = [{userOID: loginUser.userOID, fullName: loginUser.fullName}];
      signPerson = [];
    }
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);
    let formDetailValues = formInfo;
    if (this.props.params.applicationOID) {
      formDetailValues.currencyCode = info.currencyCode;
      formDetailValues.applicantOID = info.applicant && info.applicant.userOID;
      formDetailValues.customFormFields = defaultValues;
    }
    let chooserItem = deepFullCopy(chooserData['user']);
    chooserItem.title = messages('request.key206')/*自选审批人*/;

    let chooserCardOwner = deepFullCopy(chooserData['user_card']);
    chooserCardOwner.title = messages('request.key802')/*公务卡归属人*/;
    let cardOwnerName = messages('components.key3')/*公务卡归属人*/;
    chooserCardOwner.url = `${config.baseUrl}/api/application/findCardList?userOID=${additionalDefault}`;

    if (signCompanyOIDs.length > 0) {
      chooserItem.url = `/api/users/v3/search?corporationOID=${signCompanyOIDs}&companyOID=${signCompanyOIDs}`;
    }

    // 30329 【交付-麦当劳】团体申请单的选人审批进行人员过滤 -- 仅有团体申请单为选人审批模式
    chooserItem.url = `${config.baseUrl}/api/manager/v1/search`;
    let selectParticipants;
    const FieldNewOrEdit = params.applicationOID ? defaultValues : customFormFields;
    FieldNewOrEdit.map(field => {
      if (field.messageKey === 'select_participant') { // field.fieldOID  field.formValueOID
        selectParticipants = this.props.form.getFieldValue(params.applicationOID ? field.formValueOID : field.fieldOID);
      }
      if (field.fieldCode === 'carIID2') {
        thirdUserEidValue= this.state.thirdUserEid ? this.state.thirdUserEid : field.valueCode;
      }
    });
    selectParticipants && selectParticipants.map((p, i) => {
      chooserItem.url += p ? ((i ? '&userOID=' : '?userOID=') + p.userOID) : '';
    });

    // task#38113：删除团体申请单-自选审批人-手机号字段
    chooserItem.columns = [
      {
        title: messages('components.key5'/*工号*/),
        dataIndex: 'employeeID',
      },
      {
        title: messages('components.key6'/*姓名*/),
        dataIndex: 'fullName',
        render: value => {
          return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
        }
      },
      {
        title: messages('mcd.english.name'/*英文名*/),
        dataIndex: 'firstName',
        render: (value, record) => {
          if (record.firstName && record.lastName) {
            return <Popover placement="topLeft" content={`${record.firstName} ${record.lastName}`} overlayStyle={{ maxWidth: 500 }}>{`${record.firstName} ${record.lastName}`}</Popover>
          } else {
            return '-'
          }
        }
      },
      {
        title: messages('components.key8'/*部门名称*/),
        dataIndex: 'departmentName',
        render: value => {
          return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
        }
      },
      {
        title: messages('components.key189')/*职位*/,
        dataIndex: 'title',
        render: value => {
          return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
        }
      }
    ];

    let applicant = info.applicant || {}; //申请人信息
    // @ts-ignore
    let requestInfo = (
      <div style={{ position: "relative" }}>
        {!!warningList.length && (
          warningList.map((warning, index) => (
            <Alert message={warning.title}
              description={warning.message ? warning.message : '--'}
              banner
              type={warning.type === 0 ? 'warning' : 'error'}
              key={index} />
          ))
        )}
        {thirdPartyInfo.code === 'SUCCESS' && thirdPartyInfo.body && (
          <Alert
            style={{ margin: '10px 0' }}
            message={messages('request.key645', { arg1: thirdPartyInfo.body })/*提示信息：{arg1}*/}
            type="info"
            showIcon
          />
        )}
        {editTicketInfoVisible && (
          <div className="travel-header-block">
            <Row className="row-container">
              <span className="top-info-name">{applicant.fullName}</span>
              <span className="detail-info">
                {messages('request.key3'/*工号*/)}：{applicant.employeeID}
                <span className="ant-divider" />
                {messages('request.key4'/*部门*/)}：{applicant.departmentName || '-'}
                <span className="ant-divider" />
                {messages('common.user.company')/*员工公司*/}：{applicant.companyName || '-'}
              </span>
            </Row>
            <Row className="row-container">
              <span className="detail-info detail-info-first">{info.formName}：{info.businessCode}</span>
              <span className="detail-info">
                {info.submittedBy && applicant.userOID !== info.submittedBy &&
                  `，${messages('request.key447', { arg1: info.submittedName }/*由 {arg1} 代提*/)}`}
              </span>
              {this.isSetCloseEnabled && this.closeDate && (
                <span className="detail-info">
                  {messages('request.key2'/*预计关闭日期*/)}：
                  {moment(this.closeDate).format('YYYY-MM-DD')}
                </span>
              )}
              <span className="detail-info">{messages('request.key6'/*当前状态*/)}：
                {(info.closed || info.participantClosed || (info.applicationParticipant && info.applicationParticipant.closed === 1)) ?
                  messages('request.key7'/*已关闭*/) : (
                    constants.getTextByValue(String(info.status + '' + info.rejectType), 'documentStatus') ||
                    constants.getTextByValue(String(info.status), 'documentStatus')
                  )
                }
              </span>
              {info.uniformReimbursementClerk && (
                <span className="detail-info">
                  <span className="transfer-tag">{messages('request.key547')/*已转交*/}</span>
                  <span style={{ color: '#666', marginLeft: 5 }}>{info.uniformReimbursementClerk.fullName}</span>
                </span>
              )}
              <TravelPreviousVersion info={info} isPreVersion={isPreVersion} />
            </Row>
            <Row className="row-container">
              {isHasTravelBudgetDetail && (
                <span className="amount">
                  {messages('request.key9'/*总金额*/)}：
                  {currentCodeType}&nbsp;{React.Component.prototype.filterMoney(amount, queryCurrencyPrecision(currentCodeType), true)}
                </span>
              )}
              <TravelDate isLeft={!isHasTravelBudgetDetail} info={info} />
            </Row>
          </div>
        )}
        <div>
          {!editTicketInfoVisible && (
            <h3 className="header-title">
              {formInfo.formName}
            </h3>
          )}
          {!editTicketInfoVisible && (
            <Form className='form-container'>
              {formCode === 'SQ007' && isHR === true &&(
                            <FormItem {...formItemLayout} label={cardOwnerName} key="cardOwner">
                              {getFieldDecorator('cardOwner', {
                                rules: [{
                                  required: false,
                                  message: messages('common.can.not.be.empty', {name: cardOwnerName})
                                }],
                                initialValue: formDefaultValue[1]
                              })(
                                <Chooser selectorItem={chooserCardOwner}
                                        valueKey="eid"
                                        labelKey="name"
                                        disabled={false}
                                        listExtraParams={{roleType: 'TENANT'}}
                                        showClear={true}
                                        onChange={this.updateOwnerInfo}
                                        newline
                                        single/>
                              )}
                            </FormItem>
                        )}
              {info.sourceApplicationOID && (
                <FormItem {...formItemLayout}
                  label={<span><Icon type="exclamation-circle-o" />&nbsp;{messages('request.key205'/*版本号*/)}</span>}>
                  {info.version + 1}<TravelPreviousVersion info={info} isPreVersion={isPreVersion} />
                </FormItem>
              )}
              <div style={{
                margin: formInfo.formCode === 'SQ008' ? 0 : '0 0 20px 30%'
              }}>
                {customField.instructionsTag(formInfo.customFormPropertyMap, formInfo.formCode)}
              </div>
              <ExpectStopDate copyValue={copyDefaultValues} callFun={(boo, date) => this.expectStopDate(boo, date)} />
              {formCode === 'SQ008' && <GiftDeclareTitle>申报信息</GiftDeclareTitle>}
              {this.props.params.applicationOID ? (
                defaultValues.map((field, index) => {
                  let unionCompanyFlag = false
                  if (field.messageKey === 'select_company') {
                    if (field.fieldConstraint) {
                      let fieldConstraint = JSON.parse(field.fieldConstraint)
                      if (fieldConstraint.unionCompany) {
                        field.value = field.value && field.value.length > 0 ? [{ companyOID: field.value, name: field.showValue }] : []
                        unionCompanyFlag = true
                      }
                    }
                  }
                  //label
                  let label = field.fieldName;
                  if (field.messageKey === 'number') {
                    label = `${field.fieldName}${JSON.parse(field.fieldContent || '{}').unit && `(${JSON.parse(field.fieldContent || '{}').unit})`}`
                  }
                  let formFieldInfo = originalFormInfo.customFormFields.filter((item) => item.fieldOID === field.fieldOID)[0]
                  if (formFieldInfo && formFieldInfo.fieldTips) {
                    label = (<span>
                      {label}&nbsp;
                    <Tooltip title={formFieldInfo.fieldTips}>
                        <Icon type="question-circle-o" />
                      </Tooltip>
                    </span>);
                  }
                  // if (['maxnum', 'department', 'costcenter'].indexOf(field.fieldCode) > -1) {
                  //   label = (<span>
                  //     {label}&nbsp;
                  //     <Tooltip title={messages(`mcd.tip.${field.fieldCode}`/*根据公司政策规定，有其他雇员一起出差，同性雇员在可能情况下须合住双人标准房间。*/)}>
                  //       <Icon type="question-circle-o" />
                  //     </Tooltip>
                  //   </span>);
                  // }

                  //rules
                  let maxLength = (field.messageKey === 'remark' || field.messageKey === 'textArea' || field.messageKey === 'text_area') ? 200 :
                    (field.messageKey === 'input' ? 50 : undefined);
                  maxLength = field.messageKey === 'title' ? 500 : maxLength;
                  if(field.messageKey === 'input' && field.fieldCode === 'carIID'){
                    maxLength =  200 ;
                  }
                  let rules = [];
                  if (['public.assembly'].includes(field.messageKey)) { // 是公用列表
                    if (field.isHidden) { // 展示“是否显示联动开关”
                      if (field.isSwitchon) { // 联动开关为true
                        if (field.required) { // 设置了这个表单项必填
                          rules.push({
                            required: true,
                            message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
                          });
                          rules.push({
                            validator: (rule, value, callback) => {
                              if ([null, '[]'].includes(value)) {
                                callback('请填写完整');
                              } else {
                                callback();
                              }
                            }
                          });
                        } else { // 设置这个表单项不是必填
                          rules.push({
                            required: false
                          });
                        }
                      } else { // 联动开关关闭，那么这个表单项就是不必填的
                        rules.push({
                          required: false
                        });
                      }
                    } else { // 不展示联动开关
                      rules.push({
                        required: field.required,
                        message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
                      });
                      if (field.required) {
                        rules.push({
                          validator: (rule, value, callback) => {
                            if ([null, '[]'].includes(value)) {
                              callback('请填写完整');
                            } else {
                              callback();
                            }
                          }
                        });
                      }
                    }
                  } else { // 不是公用列表
                    rules.push({
                      required: field.required,
                      message: messages('common.can.not.be.empty', { name: field.fieldName })
                    });
                  }
                  maxLength && rules.push({
                    max: maxLength,
                    message: messages('common.max.characters.length', { max: maxLength })
                  });
                  if (field.fieldCode === 'businessCardID') {
                    rules.push({
                      len: 16,
                      message: field.fieldName + '必须是16位'
                    })
                  }
                  (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
                    validator: (rule, value, callback) => {
                      let emptyItem = '';
                      value && value.map(item => {
                        if (!item.name) {
                          emptyItem = messages('request.key100'/*姓名*/);
                          return
                        }
                        if (!item.certificateNo) {
                          emptyItem = messages('request.key101'/*证件号*/)
                        }
                      });
                      if (!emptyItem) {
                        callback();
                        return
                      }
                      callback(messages('common.can.not.be.empty', { name: emptyItem }))
                    }
                  });

                  return (
                    <div key={index}>
                      {index === 0 && field.messageKey !== 'applicant' && (
                        <RelatedApplication formOID={this.props.params.formOID}
                          formInfo={formInfo}
                          applicantOID={this.props.user.userOID}
                          applicationOID={this.props.params.applicationOID}
                          info={info}
                          changeHandle={(value) => { this.setState({ referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : '' }) }} />
                      )}
                      {/*展示连选日期时，不展示开始日期，结束日期*/}
                      {/*差旅申请单预算明细不在这处理*/}
                      {/*内部参与人控件配了不启用isUse为false，则不展示*/}
                      {(!isShowRangePicker || (field.messageKey !== 'start_date' && field.messageKey !== 'end_date')) && !(
                        formType == 2001 && field.messageKey === 'budget_detail'
                      ) && travelUtil.isShowParticipant(field) && !(formCodes.indexOf(formCode) > -1 && field.messageKey === 'select_participant') && (
                          (['BX', 'SQ', 'JK'].includes(field.fieldCode) && formCode === 'SQ017') ? isCustListSwitch ? <FormItem {...formItemLayout} label={label || ' '} key={field.formValueOID} colon={!!label}>
                          {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                          {getFieldDecorator(field.formValueOID, {
                            rules,
                            valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                            initialValue: unionCompanyFlag ? field.value : customField.getInitialValue(field)
                          })(
                            // customField.renderForm(field, null, customFormFields, copyDefaultValues)
                            customField.renderForm({
                              field,
                              formDetail: formDetailValues,
                              copyValue: copyDefaultValues,
                              formValues: getFieldsValue(),
                              jobId,
                              jobInfo,
                              isCustListSwitch,
                              propsParams: {
                                formDataId: this.state.info.id,
                                pkId: this.state.formInfo.id,
                                departmentOID: jobInfo.departmentOID,
                                companyOID: jobInfo.companyOID
                              },
                              //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                              onSwitchChange: this.onSwitchChange,
                              onAgentChange: this.onAgentChange,
                              onApproverChange: this.onApproverChange,
                              onProxy: this.onProxy,
                              custListParams: {
                                proxyOID: jobInfo.userOID,
                                principalOID: this.state.principalOID
                              },
                              additionalDefault,
                              userIsHr,
                              thirdUserEid: this.state.thirdUserEid,
                              excleType: formCode === 'SQ001' ? 1 : undefined,
                              hrInfo
                            })
                          )}
                        </FormItem> : <FormItem {...formItemLayout} label={label || ' '} key={field.formValueOID} colon={!!label} style={{ display: 'none' }}>
                            {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                            {getFieldDecorator(field.formValueOID, {
                              rules,
                              valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                              initialValue: unionCompanyFlag ? field.value : customField.getInitialValue(field)
                            })(
                              // customField.renderForm(field, null, customFormFields, copyDefaultValues)
                              customField.renderForm({
                                field,
                                formDetail: formDetailValues,
                                copyValue: copyDefaultValues,
                                formValues: getFieldsValue(),
                                jobId,
                                jobInfo,
                                isCustListSwitch,
                                propsParams: {
                                  formDataId: this.state.info.id,
                                  pkId: this.state.formInfo.id,
                                  departmentOID: jobInfo.departmentOID,
                                  companyOID: jobInfo.companyOID
                                },
                                //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                                onSwitchChange: this.onSwitchChange,
                                onAgentChange: this.onAgentChange,
                                onApproverChange: this.onApproverChange,
                                onProxy: this.onProxy,
                                custListParams: {
                                  proxyOID: jobInfo.userOID,
                                  principalOID: this.state.principalOID
                                },
                                additionalDefault,
                                userIsHr,
                                thirdUserEid: this.state.thirdUserEid,
                                excleType: formCode === 'SQ001' ? 1 : undefined,
                                hrInfo
                              })
                            )}
                          </FormItem>
                         : <FormItem {...formItemLayout} label={label || ' '} key={field.formValueOID} colon={!!label}>
                            {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                            {getFieldDecorator(field.formValueOID, {
                              rules,
                              valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                              initialValue: unionCompanyFlag ? field.value : customField.getInitialValue(field)
                            })(
                              // customField.renderForm(field, null, customFormFields, copyDefaultValues)
                              customField.renderForm({
                                field,
                                formDetail: formDetailValues,
                                copyValue: copyDefaultValues,
                                formValues: getFieldsValue(),
                                jobId,
                                jobInfo,
                                isCustListSwitch,
                                propsParams: {
                                  formDataId: this.state.info.id,
                                  pkId: this.state.formInfo.id,
                                  departmentOID: jobInfo.departmentOID,
                                  companyOID: jobInfo.companyOID
                                },
                                //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                                onSwitchChange: this.onSwitchChange,
                                onAgentChange: this.onAgentChange,
                                onApproverChange: this.onApproverChange,
                                onProxy: this.onProxy,
                                custListParams: {
                                  proxyOID: jobInfo.userOID,
                                  principalOID: this.state.principalOID
                                },
                                additionalDefault,
                                userIsHr,
                                thirdUserEid: this.state.thirdUserEid,
                                excleType: formCode === 'SQ001' ? 1 : undefined,
                                hrInfo
                              })
                            )}
                          </FormItem>
                        )}
                      {/*差旅连选日期，预计停用日期的控件*/}
                      {isShowRangePicker && this.isSetCloseEnabled && field.messageKey === 'range_picker' && (
                        <FormItem {...formItemLayout} label={messages('request.key2'/*预计关闭日期*/)}>
                          <DatePicker disabled={true} value={this.closeDate} format="YYYY-MM-DD" style={{ width: '100%' }} />
                        </FormItem>
                      )}
                      {/*关联申请单在申请人下面*/}
                      {index === 0 && field.messageKey === 'applicant' && (
                        <RelatedApplication formOID={this.props.params.formOID}
                          formInfo={formInfo}
                          applicantOID={this.props.user.userOID}
                          applicationOID={this.props.params.applicationOID}
                          info={info}
                          changeHandle={(value) => { this.setState({ referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : '' }) }} />
                      )}
                      {travelUtil.isShowAutoLoan(field, formType, formInfo.customFormPropertyMap, false, info && info.loanBillOID, info && info.sourceApplicationOID, isProxy) && (
                        <FormItem {...formItemLayout} label={messages('request.key566')/*借款申请*/} key="autoLoan">
                          {this.renderAutoLoan()}
                        </FormItem>
                      )}
                    </div>
                  )
                })
              ) : (
                  customFormFields.filter(i=>{
                    if(!fafangleixingFlag && !constants.CuxRender({formCode}).FORMCODE && i.fieldCode == 'fafangleixing'){
                      return;
                    }
                    return i;
                  }).map((field, index) => {
                    //label
                    let label = field.fieldName;
                    if (field.messageKey === 'number') {
                      label = `${field.fieldName}${JSON.parse(field.fieldContent || '{}').unit && `(${JSON.parse(field.fieldContent || '{}').unit})`}`
                    }
                    let formFieldInfo = originalFormInfo.customFormFields.filter((item) => item.fieldOID === field.fieldOID)[0]
                    if (formFieldInfo && formFieldInfo.fieldTips) {
                      label = (<span>
                        {label}&nbsp;
                    <Tooltip title={formFieldInfo.fieldTips}>
                          <Icon type="question-circle-o" />
                        </Tooltip>
                      </span>);
                    }
                    // if (['maxnum', 'department', 'costcenter'].indexOf(field.fieldCode) > -1) {
                    //   label = (<span>
                    //     {label}&nbsp;
                    //     <Tooltip title={messages(`mcd.tip.${field.fieldCode}`/*根据公司政策规定，有其他雇员一起出差，同性雇员在可能情况下须合住双人标准房间。*/)}>
                    //       <Icon type="question-circle-o" />
                    //     </Tooltip>
                    //   </span>);
                    // }

                    //rules
                    let maxLength = (field.messageKey === 'remark' || field.messageKey === 'textArea') ? 200 : (field.messageKey === 'input' ? 50 : undefined);
                    maxLength = field.messageKey === 'title' ? 500 : maxLength;
                    maxLength = field.messageKey === 'text_area' ? 1000 : maxLength;
                    if(field.messageKey === 'input' && field.fieldCode === 'carIID'){
                      maxLength =  200 ;
                    }
                    let rules = [];
                    if (['public.assembly'].includes(field.messageKey)) { // 是公用列表
                      if (field.isHidden) { // 展示“是否显示联动开关”
                        if (field.isSwitchOn) { // 联动开关为true
                          if (field.required) { // 设置了这个表单项必填
                            rules.push({
                              required: true,
                              message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
                            });
                            rules.push({
                              validator: (rule, value, callback) => {
                                if ([null, '[]'].includes(value)) {
                                  callback('请填写完整');
                                } else {
                                  callback();
                                }
                              }
                            });
                          } else { // 设置这个表单项不是必填
                            rules.push({
                              required: false
                            });
                          }
                        } else { // 联动开关关闭，那么这个表单项就是不必填的
                          rules.push({
                            required: false
                          });
                        }
                      } else { // 不展示联动开关
                        rules.push({
                          required: field.required,
                          message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
                        });
                        if (field.required) {
                          rules.push({
                            validator: (rule, value, callback) => {
                              if ([null, '[]'].includes(value)) {
                                callback('请填写完整');
                              } else {
                                callback();
                              }
                            }
                          });
                        }
                      }
                    } else { // 不是公用列表
                      rules.push({
                        required: field.required,
                        message: messages('common.can.not.be.empty', { name: field.fieldName })
                      });
                    }
                    if (field.fieldCode === 'businessCardID') {
                      rules.push({
                        len: 16,
                        message: field.fieldName + '必须是16位'
                      })
                    }
                    field.fieldName !== messages('enterprise-manage.key505'/*默认额度*/) && field.fieldName !== messages('enterprise-manage.key506'/*当前额度*/) && field.fieldName !== messages('enterprise-manage.key507'/*政策规定额度*/) && maxLength && rules.push({
                      max: maxLength,
                      message: messages('common.max.characters.length', { max: maxLength })
                    });
                    (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
                      validator: (rule, value, callback) => {
                        let emptyItem = '';
                        value && value.map(item => {
                          if (!item.name) {
                            emptyItem = messages('request.key100'/*姓名*/);
                            return
                          }
                          if ((JSON.parse(field.fieldContent || '{}').isContainCard || field.messageKey === 'out_participant_name') && !item.certificateNo) {
                            emptyItem = messages('request.key101'/*证件号*/)
                          }
                        });
                        if (!emptyItem) {
                          callback();
                          return
                        }
                        callback(messages('common.can.not.be.empty', { name: emptyItem }))
                      }
                    });

                    //initialValue
                    let fieldDefaultValue = {};
                    let costCenterItemOID = ''
                    formDefaultValue.map(item => {
                      item.fieldOID === field.fieldOID && (fieldDefaultValue = item)
                      item.fieldName === '费用承担部门' && field.messageKey === 'select_user' && (costCenterItemOID = item.value)
                    });
                    field.messageKey === 'select_user' && (fieldDefaultValue = {...fieldDefaultValue, costCenterItemOID})
                    if (fieldDefaultValue.fieldName === '费用确认人' && !fieldDefaultValue.name) {
                      fieldDefaultValue.showValue = this.props.user.fullName;
                    }
                    console.log('fieldDefaultValue', fieldDefaultValue)
                    return (
                      <div key={index}>
                        {index === 0 && field.messageKey !== 'applicant' && (
                          <RelatedApplication formOID={this.props.params.formOID}
                            formInfo={formInfo}
                            applicantOID={this.props.user.userOID}
                            applicationOID={this.props.params.applicationOID}
                            changeHandle={(value) => { this.setState({ referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : '' }) }} />
                        )}
                        {/*展示连选日期时，不展示开始日期，结束日期*/}
                        {/*差旅申请单预算明细不在这处理*/}
                        {/*内部参与人控件配了不启用isUse为false，则不展示*/}
                        {(!isShowRangePicker || (field.messageKey !== 'start_date' && field.messageKey !== 'end_date')) && !(
                          formType == 2001 && field.messageKey === 'budget_detail'
                        ) && travelUtil.isShowParticipant(field) && !(formCodes.indexOf(formCode) > -1 && field.messageKey === 'select_participant') && (
                            (['BX', 'SQ', 'JK'].includes(field.fieldCode) && formCode === 'SQ017') ? isCustListSwitch ? <FormItem {...formItemLayout} label={label || ' '} key={field.fieldOID} colon={!!label}>
                            {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                            {getFieldDecorator(field.fieldOID, {
                              rules,
                              valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                              initialValue: customField.getDefaultValue(field, fieldDefaultValue, formCode, jobInfo)
                            })(
                              // customField.renderForm(field, fieldDefaultValue,customFormFields , copyDefaultValues)
                              customField.renderForm({
                                field,
                                fieldDefaultValue,
                                formDetail: formInfo,
                                copyValue: copyDefaultValues,
                                formValues: getFieldsValue(),
                                jobId,
                                jobInfo,
                                isCustListSwitch,
                                propsParams: {
                                  departmentOID: jobInfo.departmentOID,
                                  companyOID: jobInfo.companyOID
                                },
                                //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                                onSwitchChange: this.onSwitchChange,
                                onAgentChange: this.onAgentChange,
                                onApproverChange: this.onApproverChange,
                                onProxy: this.onProxy,
                                custListParams: {
                                  proxyOID: jobInfo.userOID,
                                  principalOID: this.state.principalOID
                                },
                                additionalDefault,
                                userIsHr,
                                thirdUserEid: this.state.thirdUserEid,
                                excleType: formCode === 'SQ001' ? 1 : undefined,
                                hrInfo
                              })
                            )}
                          </FormItem> : <FormItem {...formItemLayout} label={label || ' '} key={field.fieldOID} colon={!!label} style={{ display: 'none' }}>
                            {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                            {getFieldDecorator(field.fieldOID, {
                              rules,
                              valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                              initialValue: customField.getDefaultValue(field, fieldDefaultValue, formCode, jobInfo)
                            })(
                              // customField.renderForm(field, fieldDefaultValue,customFormFields , copyDefaultValues)
                              customField.renderForm({
                                field,
                                fieldDefaultValue,
                                formDetail: formInfo,
                                copyValue: copyDefaultValues,
                                formValues: getFieldsValue(),
                                jobId,
                                jobInfo,
                                isCustListSwitch,
                                propsParams: {
                                  departmentOID: jobInfo.departmentOID,
                                  companyOID: jobInfo.companyOID
                                },
                                //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                                onSwitchChange: this.onSwitchChange,
                                onAgentChange: this.onAgentChange,
                                onApproverChange: this.onApproverChange,
                                onProxy: this.onProxy,
                                custListParams: {
                                  proxyOID: jobInfo.userOID,
                                  principalOID: this.state.principalOID
                                },
                                additionalDefault,
                                userIsHr,
                                thirdUserEid: this.state.thirdUserEid,
                                excleType: formCode === 'SQ001' ? 1 : undefined,
                                hrInfo
                              }))}
                              </FormItem> : <FormItem {...formItemLayout} label={label || ' '} key={field.fieldOID} colon={!!label}>
                              {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                              {getFieldDecorator(field.fieldOID, {
                                rules,
                                valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                                initialValue: customField.getDefaultValue(field, fieldDefaultValue, formCode, jobInfo)
                              })(
                                // customField.renderForm(field, fieldDefaultValue,customFormFields , copyDefaultValues)
                                customField.renderForm({
                                  field,
                                  fieldDefaultValue,
                                  formDetail: formInfo,
                                  copyValue: copyDefaultValues,
                                  formValues: getFieldsValue(),
                                  jobId,
                                  jobInfo,
                                  isCustListSwitch,
                                  propsParams: {
                                    departmentOID: jobInfo.departmentOID,
                                    companyOID: jobInfo.companyOID
                                  },
                                  //isSwitchChecked: this.state.hiddenRequiredObj[field.fieldOID],
                                  onSwitchChange: this.onSwitchChange,
                                  onAgentChange: this.onAgentChange,
                                  onApproverChange: this.onApproverChange,
                                  onProxy: this.onProxy,
                                  custListParams: {
                                    proxyOID: jobInfo.userOID,
                                    principalOID: this.state.principalOID
                                  },
                                  additionalDefault,
                                  userIsHr,
                                  thirdUserEid: this.state.thirdUserEid,
                                  excleType: formCode === 'SQ001' ? 1 : undefined,
                                  hrInfo
                                })
                              )}
                            </FormItem>
                          )}
                        {/*差旅连选日期，预计停用日期的控件*/}
                        {isShowRangePicker && this.isSetCloseEnabled && field.messageKey === 'range_picker' && (
                          <FormItem {...formItemLayout} label={messages('request.key2'/*预计关闭日期*/)}>
                            <DatePicker disabled={true} value={this.closeDate} format="YYYY-MM-DD" style={{ width: '100%' }} />
                          </FormItem>
                        )}
                        {/*关联申请单在申请人下面*/}
                        {index === 0 && field.messageKey === 'applicant' && (
                          <RelatedApplication formOID={this.props.params.formOID}
                            formInfo={formInfo}
                            applicantOID={this.props.user.userOID}
                            applicationOID={this.props.params.applicationOID}
                            changeHandle={(value) => { this.setState({ referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : '' }) }} />
                        )}
                        {travelUtil.isShowAutoLoan(field, formType, formInfo.customFormPropertyMap, false, info && info.loanBillOID, info && info.sourceApplicationOID, isProxy) && (
                          <FormItem {...formItemLayout} label={messages('request.key566')/*借款申请*/} key="autoLoan">
                            {this.renderAutoLoan()}
                          </FormItem>
                        )}
                      </div>
                    )
                  })
                )}
              {signEnable && signReset && formCode === 'MCD3001' && (
              <FormItem {...formItemLayout} label={signName} key="addSign">
                {getFieldDecorator('addSign', {
                  rules: [{
                    required: formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.enableCounterSignForSubmitterMustWriter === 'true',
                    message: messages('common.can.not.be.empty', {name: signName})
                  }],
                  initialValue: signPerson
                })(
                  <Chooser selectorItem={chooserItem}
                           valueKey="userOID"
                           labelKey="fullName"
                           onlyNeed="userOID"
                           listExtraParams={{roleType: 'TENANT'}}
                           showArrow={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.countersignType === '2'}
                           showClear={false}
                           // additionalDefault={additionalDefault}
                           newline
                           single/>
                )}
              </FormItem>
            )}
              {formCode === 'SQ017' && isCustListSwitch && <FormItem {...formItemLayout} label='账本及消费'>
                  <Popover placement="topLeft" content="我的账本，滴滴消费，公务卡消费">
                    <Select disabled defaultValue="我的账本，滴滴消费，公务卡消费" showArrow={false}>
                      <Option value="我的账本，滴滴消费，公务卡消费">我的账本，滴滴消费，公务卡消费</Option>
                    </Select>
                  </Popover>
              </FormItem>}
              {formCode === 'SQ017' && isCustListSwitch && <FormItem {...formItemLayout} label='还款单'>
                <Popover placement="topLeft" content="还款单">
                    <Select disabled defaultValue="还款单" showArrow={false}>
                      <Option value="还款单">还款单</Option>
                    </Select>
                  </Popover>
              </FormItem>}
              {formCode === 'SQ008' && <GiftDeclare form={this.props.form}></GiftDeclare>}
              {formCode === 'SQ005' ? <FormItem {...formItemLayout} label="提示">
                <p style={{ margin: 0 }}>在提交公务卡申请单后，请关注以下内容：</p>
                <p style={{ margin: 0 }}>1、在财务审批人审批通过后，进入仪表盘，点击滚动页面中“公司信用卡操作细则”，下载并打印“公务卡申请表-个人承债-A4”，并按SAMPLE将打星号的必填项全部填写完整。</p>
                <p style={{ margin: 0 }}>2、连同个人身份证明复印件一并邮寄至资金部，进行纸质资料审核环节。</p>
              </FormItem> : formCode === 'SQ006' ? <FormItem {...formItemLayout} label="提示">
                {/* <p style={{ margin: 0 }}>公司信息卡透支额度规定如下:</p> */}
                <p style={{ margin: 0 }}>因业务需要，可申请临时调增公司信用卡的透支额度，经财务总监/市场财务负责人批准后由财务部通知银行予以调整；最终的透支额度由银行决定。</p>
                {/* <p style={{ margin: 0 }}>• 职级C5及以下---------------------------人民币10,000元或等值外币</p> */}
                {/* <p style={{ margin: 0 }}>• 职级C6，C7-----------------------------人民币50,000元或等值外币</p> */}
                {/* <p style={{ margin: 0 }}>• 职级C8及以上---------------------------人民币100,000元或等值外币</p> */}
              </FormItem> : formCode === 'SQ010' || formCode === 'SQ020' ? <FormItem {...formItemLayout} label="提示">
                <p style={{ margin: 0 }}>我已知晓这将会给公司造成损失，我声明公司有权向我追补该损失。</p>
              </FormItem> : ''
              }
              {formCode === 'SQ024' && hrInfo && <GreenCode form={this.props.form} user={this.props.user} hrInfo={hrInfo}
                                                            showVisible={() => this.setState({showSubmitBtn: true})}
                                                            hideVisible={() => this.setState({showSubmitBtn: false})}
              ></GreenCode>}
            </Form>
          )}
        </div>
      </div>
    );
    let travelValuesInfo = (
      <div className="travel-ticket-info travel-header-info">
        <h3 className="header-title">
          {messages('request.key10'/*申请单详情*/)}
          <a className="edit-travel-header-info" onClick={this.goTravelEdit}>
            {messages('common.edit')/*编辑*/}
          </a>
        </h3>
        {customField.renderFields(valuesOnlyForShow, info, info.applicant, '', signName)}
        <div style={{ width: '100%' }}>
          <img src={lowCarbonTravel} style={{ width: '100%', height: 'auto', display: 'block' }} alt="Low Carbon Travel" />
        </div>
      </div>
    );
    let travelTicketInfo = (
      <div className="travel-ticket-info">
        <h3 className="header-title">{messages('request.key715'/*行程明细*/)}</h3>
        {formType === 2001 && this.state.manageType &&
          formInfo.customFormPropertyMap && this.props.params.applicationOID && defaultValues.length > 0 && (
            <TravelType updateTotalBudget={(total, clear, isHaveRoute, isRepeatSubsidy, itineraryData, isRefreshBudget) => this.updateTotalBudget(total, clear, isHaveRoute, isRepeatSubsidy, itineraryData, isRefreshBudget)}
              beforeAddSubsidyToSave={(boo) => this.beforeAddSubsidyToSave(boo)}
              infoDetail={info}
              formIsChange={formIsChange}
              isSaveBtnClicked={isSaveBtnClicked}
              setInfo={
                {
                  oid: this.props.params.applicationOID,
                  travelInfo: formInfo,
                  defaultValue: defaultValues,
                  clearSubsidy: haveClear,
                  total,
                  isFirstSave: isFirstSave,
                  formOID: this.props.params.formOID
                }
              } />
          )}

        {formType === 2001 && !this.state.manageType && dateChage && this.props.params.applicationOID && !loading && (
          <TravelElementType updateTotalBudget={(total, clear, isHaveRoute, isRepeatSubsidy) => this.updateTotalBudget(total, clear, isHaveRoute, isRepeatSubsidy)}
            beforeAddSubsidyToSave={(boo) => this.beforeAddSubsidyToSave(boo)}
            updateTravelItinerarys={travelItinerarys => this.setState({ travelItinerarys: travelItinerarys })}
            infoDetail={info}
            formIsChange={formIsChange}
            setInfo={
              {
                oid: this.props.params.applicationOID,
                travelInfo: formInfo,
                defaultValue: defaultValues,
                clearSubsidy: haveClear,
                formOID: this.props.params.formOID,
                travelElement: !this.state.manageType,
                travelElementServiceName,
                travelItinerarys
              }
            } />
        )}
      </div>
    );
    let travelBudgetDetail = (
      <div className="travel-ticket-info" style={{ display: 'none' }}>
        <Form>
          {valuesOnlyForShow.map((field, index) => {
            return field.messageKey === 'budget_detail' && editTicketInfoVisible && (
              <FormItem key={field.formValueOID}>
                {getFieldDecorator('travelBudgetDetail', {
                  rules: [
                    {
                      validator: (item, value, callback) => {
                        if (field.required && (!value || !value.budgetDetail || !value.budgetDetail.length)) {
                          callback(messages('common.can.not.be.empty', { name: field.fieldName }));
                        }
                        callback();
                      }
                    }
                  ],
                  valuePropName: 'value',
                  initialValue: travelBudgetDetailObj ? travelBudgetDetailObj : undefined
                })(
                  <ExpenseTypeModal
                    fieldName={field.fieldName}
                    skinMode="skin01"
                    formOID={field.formOID}
                    jobInfo={jobInfo}
                    formDetail={formDetailValues}
                    copyValue={copyDefaultValues}
                  />
                )}
              </FormItem>
            )
          })}
        </Form>
        {travelUtil.isShowAutoLoan({}, formType, formInfo.customFormPropertyMap, editTicketInfoVisible, info && info.loanBillOID, info && info.sourceApplicationOID, isProxy) && (
          <Row style={{ marginBottom: '32px' }}>
            <Col span={2}>{messages('request.key566')/*借款申请*/}:</Col>
            <Col span={20}>{this.renderAutoLoan()}</Col>
          </Row>
        )}
      </div>
    );
    return (
      <div className={`new-request ${(editTicketInfoVisible && tabKey === 'requestInfo') ? 'background-transparent new-travel-request' : ''}`} style={{ minHeight: "calc(100vh - 80px) !important" }}>
        <Spin spinning={loading}>
          {(!!approvalHistory.length || (!approvalHistory.length && editTicketInfoVisible) || budgetExplainNumber > 0) && (
            <Tabs type="card" className={editTicketInfoVisible ? 'travel-tabs-info' : ''}
              onChange={key => this.setState({ tabKey: key })}>
              <TabPane tab={messages('request.key11'/*申请单信息*/)} key="requestInfo">{requestInfo}</TabPane>
              {budgetExplainNumber > 0 && false && (
                <TabPane tab={messages('request.key584')/*预算执行信息*/} key="budgetExplain">
                  <BudgetExplain documentType="EXP_REQUISITION" documentId={info.applicationOID} />
                </TabPane>
              )}
              {!!approvalHistory.length && (
                <TabPane tab={messages('request.key12'/*审批历史*/)} key="approvals">
                  <ApproveHistory approvalChains={info.approvalChains}
                    isShowReply={false}
                    businessCode={info.businessCode}
                    formCode={info.formCode}
                    approvalHistory={approvalHistory}
                    applicantInfo={info.applicant || {}} />
                </TabPane>
              )}
            </Tabs>
          )}
          {!approvalHistory.length && !editTicketInfoVisible && !budgetExplainNumber && requestInfo}
          {editTicketInfoVisible && tabKey === 'requestInfo' && travelValuesInfo}
          {editTicketInfoVisible && tabKey === 'requestInfo' && travelTicketInfo}
          {editTicketInfoVisible && isHasTravelBudgetDetail && tabKey === 'requestInfo' && travelBudgetDetail}
        </Spin>

        <Affix offsetBottom={0} className="bottom-bar">
          {/* modify by mengsha.wang@huilianyi.com 需求4053 */}
          {formType && (
            formType === 2001 ? (
              <div>
                {editTicketInfoVisible && (
                  <Button type="primary" onClick={this.handleSubmit} loading={submitLoading}>{messages('mcd.request.submit'/*提交申请单*/)}</Button>
                )}
                {editTicketInfoVisible && (
                  <Popconfirm title={messages('common.confirm.delete')} placement="topRight" onConfirm={this.handleDelete}>
                    <Button className="delete-btn" loading={deleteLoading}>{messages('common.delete')}</Button>
                  </Popconfirm>
                )}
                <Button loading={saveLoading} type={editTicketInfoVisible ? 'default' : 'primary'} onClick={this.handleSave}>
                  {params.applicationOID ? messages('mcd.request.save') : messages('request.key523')/*保存并添加行程*/}
                </Button>
                <Button onClick={editTicketInfoVisible || !params.applicationOID ? this.goBack : () => this.cancelTravelEdit(valuesOnlyForShow)}>
                  {editTicketInfoVisible || !params.applicationOID ? messages('common.back') : messages('common.cancel')}
                </Button>
              </div>
            ) : (
              <div>
                <ReactIF rif={formCode === 'SQ024'}>
                  <Modal
                    title="提交二次确认"
                    visible={this.state.greenCodeAlertVisible}
                    okText="确认"
                    cancelText="取消"
                    footer={[
                        <Button key="back" loading={submitLoading} onClick={()=> this.setState({
                          greenCodeAlertVisible: false,
                        })}>
                          取消
                        </Button>,
                        <Button key="submit" type="primary" loading={submitLoading} onClick={this.handleSubmit}>
                          确认提交
                        </Button>]}
                  >
                    <Alert
                      message="离职自查申请单二次确认警告"
                      description="发起离职自查申请单后账号将被禁用，申请通过后将通过邮件提醒，是否确认继续提交申请。"
                      type="warning"
                      showIcon
                    />
                  </Modal>
                </ReactIF>
                {
                  showSubmitBtn && formCode && (formCode !== 'SQ002' && formCode !== 'SQ003' && formCode !== 'SQ004' ) ? (
                    <Button type="primary" onClick={ formCode === 'SQ024'? (()=>{this.setState({
                      greenCodeAlertVisible: true,
                    })}) : this.handleSubmit} loading={submitLoading}>{messages('mcd.request.submit')}</Button>
                  ) : ''
                }
                {params.applicationOID && (
                  <Popconfirm title={messages('common.confirm.delete')} placement="topRight" onConfirm={this.handleDelete}>
                    <Button className="delete-btn" loading={deleteLoading}>{messages('common.delete')}</Button>
                  </Popconfirm>
                )}
                {formCode !== 'SQ024'/*绿码申请不需要保存*/ &&
                  <Button onClick={this.handleSave} loading={saveLoading}>{messages('mcd.request.save')}</Button>}
                <Button onClick={this.goBack}>{messages('common.back')}</Button>
              </div>
            )
          )}
          {
            formType === 2001 && editTicketInfoVisible && isHasTravelBudgetDetail && <Row className="total-budget">
              <span className="total">
                {messages('request.key207'/*总金额*/)}:{currentCodeType}&nbsp;{React.Component.prototype.filterMoney(amount, queryCurrencyPrecision(currentCodeType), true)}
              </span>
            </Row>
          }

        </Affix>
        <Modal title={messages('request.key618')/*预订设置*/}
          visible={subsidyCtrl.isShowModal}
          onOk={() => this.goSubmitTravel(false)}
          onCancel={this.cancelSubmit}
          width={'50%'}
          className="travel-request-uniform-modal"
          okText={messages('request.key211'/*确定*/)}
          cancelText={messages('request.key181'/*返回*/)}/*"返回"*/
        >
          <Form>
            {
              subsidyCtrl.flight && <Row>
                <Col span={6} style={{ marginTop: 9 }}>
                  <span>{messages('request.key619')/*统一订机票*/}：</span>
                </Col>
                <Col span={4} style={{ marginTop: 7 }}>
                  {isFlightSwitch && (
                    <Switch
                      disabled={!!info.sourceApplicationOID}
                      checked={info.travelApplication.hasOwnProperty("uniformBooking") ? info.travelApplication.uniformBooking : isFlight}
                      size="small"
                      onChange={() => this.onChangeSwitch('flight')}
                    />
                  )}
                </Col>
                <Col span={14} style={{ marginTop: isFlight ? 0 : 8 }}>
                  {
                    (info.travelApplication.hasOwnProperty("uniformBooking") ? info.travelApplication.uniformBooking : isFlight)
                      ? <FormItem {...formItemLayoutModal} label={messages('request.key620')/*预订人*/}>
                        {getFieldDecorator('bookingClerkOID', {
                          initialValue: info.travelApplication.bookingClerkOID ? info.travelApplication.bookingClerkOID : subsidyCtrl.selectPerson[0] ? subsidyCtrl.selectPerson[0].oid : ""
                        })(
                          <Select disabled={info.sourceApplicationOID ? true : false}>
                            {
                              subsidyCtrl.selectPerson.map(p => {
                                return (
                                  <Option opt={p} key={p.oid}>
                                    {p.role && (<span>{p.role}-</span>)}
                                    {p.name}
                                  </Option>
                                )
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                      : <span>
                        {messages('request.key459', { arg1: info.createdName }/*参与人各自预订，外部参与人由{arg1}代订*/)}
                      </span>
                  }
                </Col>
              </Row>
            }
            {subsidyCtrl.flightPlatform && (
              <Row>
                <Col span={10} style={{ marginTop: 9 }}>
                  <span>{messages('request.key621')/*统一订机票（订票平台）*/}：</span>
                </Col>
                <Col span={14}>
                  <FormItem {...formItemLayoutModal} label={messages('request.key620')/*预订人*/}>
                    {getFieldDecorator('platformBookingClerkOID', {
                      initialValue: (info.travelApplication && info.travelApplication.platformBookingClerkOID) ? info.travelApplication.platformBookingClerkOID : (
                        subsidyCtrl.platformPerson[0] ? subsidyCtrl.platformPerson[0].oid : ""
                      )
                    })(
                      <Select disabled={!!info.sourceApplicationOID}>
                        {
                          subsidyCtrl.platformPerson.map(p => {
                            return (
                              <Option opt={p} key={p.oid}>
                                {p.name}
                              </Option>
                            )
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
            )}
            {
              subsidyCtrl.train && <Row>
                <Col span={6} style={{ marginTop: 9 }}>
                  <span>{messages('request.key214'/*统一订火车票*/)}：</span>
                </Col>
                <Col span={4} style={{ marginTop: 7 }}>
                  {isTrainSwitch && (
                    <Switch
                      disabled={!!info.sourceApplicationOID}
                      checked={info.travelApplication.hasOwnProperty("trainUniformBooking") ? info.travelApplication.trainUniformBooking : isTrain}
                      size="small"
                      onChange={() => this.onChangeSwitch('train')}
                    />
                  )}
                </Col>
                <Col span={14} style={{ marginTop: isTrain ? 0 : 8 }}>
                  {
                    (info.travelApplication.hasOwnProperty("trainUniformBooking") ? info.travelApplication.trainUniformBooking : isTrain)
                      ? <FormItem {...formItemLayoutModal} label={messages('request.key620')/*预订人*/}>
                        {getFieldDecorator('trainBookingClerkOID', {
                          initialValue: info.travelApplication.trainBookingClerkOID ? info.travelApplication.trainBookingClerkOID : subsidyCtrl.selectPerson[0] ? subsidyCtrl.selectPerson[0].oid : ""
                        })(
                          <Select disabled={info.sourceApplicationOID ? true : false}>
                            {
                              subsidyCtrl.selectPerson.map(p => {
                                return (
                                  <Option opt={p} key={p.oid}>
                                    {p.role && (<span>{p.role}-</span>)}
                                    {p.name}
                                  </Option>
                                )
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                      : <span>
                        {messages('request.key459', { arg1: info.createdName }/*参与人各自预订，外部参与人由{arg1}代订*/)}
                      </span>
                  }
                </Col>
              </Row>
            }
            {subsidyCtrl.dining && (
              <Row>
                <Col span={6} style={{ marginTop: 9 }}>
                  <span>{messages('request.key622')/*统一订餐*/}：</span>
                </Col>
                <Col span={4} style={{ marginTop: 7 }}>
                  {isDiningSwitch && (
                    <Switch
                      disabled={!!info.sourceApplicationOID}
                      checked={info.travelApplication.hasOwnProperty("diningUniformBooking") ? info.travelApplication.diningUniformBooking : isDining}
                      size="small"
                      onChange={() => this.onChangeSwitch('dining')}
                    />
                  )}
                </Col>
                <Col span={14} style={{ marginTop: isTrain ? 0 : 8 }}>
                  {
                    (info.travelApplication.hasOwnProperty("diningUniformBooking") ? info.travelApplication.diningUniformBooking : isDining)
                      ? <FormItem {...formItemLayoutModal} label={messages('request.key620')/*预订人*/}>
                        {getFieldDecorator('diningBookingClerkOID', {
                          initialValue: info.travelApplication.diningBookingClerkOID ? info.travelApplication.diningBookingClerkOID : subsidyCtrl.selectPerson[0] ? subsidyCtrl.selectPerson[0].oid : ""
                        })(
                          <Select disabled={info.sourceApplicationOID ? true : false}>
                            {
                              subsidyCtrl.selectPerson.map(p => {
                                return (
                                  <Option opt={p} key={p.oid}>
                                    {p.role && (<span>{p.role}-</span>)}
                                    {p.name}
                                  </Option>
                                )
                              })
                            }
                          </Select>
                        )}
                      </FormItem>
                      : <span>
                        {messages('request.key459', { arg1: info.createdName }/*参与人各自预订，外部参与人由{arg1}代订*/)}
                      </span>
                  }
                </Col>
              </Row>
            )}
            {
              subsidyCtrl.hotel && <Row>
                <Col span={6} style={{ marginTop: 9 }}>
                  <span>{messages('request.key216'/*统一订酒店*/)}：</span>
                </Col>
                <Col span={4} style={{ marginTop: 7 }}>
                  {isHotelSwitch && (
                    <Switch
                      disabled={!!info.sourceApplicationOID}
                      checked={info.travelApplication.hasOwnProperty("hotelUniformBooking") ? info.travelApplication.hotelUniformBooking : isHotel}
                      size="small"
                      onChange={() => this.onChangeSwitch('hotel')}
                    />
                  )}
                </Col>
                <Col span={14} style={{ marginTop: isHotel ? 0 : 8 }}>
                  {
                    (info.travelApplication.hasOwnProperty("hotelUniformBooking") ? info.travelApplication.hotelUniformBooking : isHotel) ? <FormItem {...formItemLayoutModal} label={messages('request.key620')/*预订人*/}>
                      {getFieldDecorator('hotelBookingClerkOID', {
                        initialValue: info.travelApplication.hotelBookingClerkOID ? info.travelApplication.hotelBookingClerkOID : subsidyCtrl.selectPerson[0] ? subsidyCtrl.selectPerson[0].oid : ""
                      })(
                        <Select disabled={info.sourceApplicationOID ? true : false}>
                          {
                            subsidyCtrl.selectPerson.map(p => {
                              return (
                                <Option opt={p} key={p.oid}>
                                  {p.role && (<span>{p.role}-</span>)}
                                  {p.name}
                                </Option>
                              )
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                      : (<div>
                        <p>{messages('request.key460', { arg1: info.createdName }/*请选择合住房间的预订人，非合住人员各自订票，外部参与人由 {arg1} 预订*/)}</p>
                        {(maxHotel.maleRoomNumber > 0 || maxHotel.femaleRoomNumber > 0) &&
                          <FormItem {...formItemLayoutModal} label={messages('request.key218'/*合住房间预订人*/)}>
                            {getFieldDecorator('randomHotelPeopleBtn')(
                              <Button type='primary' loading={randomHotel} ghost disabled={info.sourceApplicationOID ? true : false} onClick={this.createHotelPeople}>{messages('request.key219'/*随机*/)}</Button>
                            )}
                          </FormItem>
                        }
                        {
                          (maxHotel.maleRoomNumber > 0) && <FormItem {...formItemLayoutModal} label={messages('request.key220'/*男士*/)}>
                            {getFieldDecorator('travelHotelBookingMaleClerks', {
                              initialValue: (info.travelApplication.travelHotelBookingMaleClerks && info.sourceApplicationOID) ? info.travelApplication.travelHotelBookingMaleClerks : []
                            })(
                              <Select disabled={info.sourceApplicationOID ? true : false}
                                mode="multiple"
                                optionFilterProp="children"
                              >
                                {
                                  maxHotel.maleUsers.map(p => {
                                    return (
                                      <Option opt={p} key={p.userOID}>{p.fullName}</Option>
                                    )
                                  })
                                }
                              </Select>
                            )}
                          </FormItem>
                        }
                        {
                          (maxHotel.femaleRoomNumber > 0) && <FormItem {...formItemLayoutModal} label={messages('request.key221'/*女士*/)}>
                            {getFieldDecorator('travelHotelBookingFemaleClerks', {
                              initialValue: (info.travelApplication.travelHotelBookingFemaleClerks && info.sourceApplicationOID) ? info.travelApplication.travelHotelBookingFemaleClerks : []
                            })(
                              <Select disabled={info.sourceApplicationOID ? true : false}
                                mode="multiple"
                                optionFilterProp="children"
                              >
                                {
                                  maxHotel.femaleUsers.map(p => {
                                    return (
                                      <Option opt={p} key={p.userOID}>{p.fullName}</Option>
                                    )
                                  })
                                }
                              </Select>
                            )}
                          </FormItem>
                        }

                      </div>)
                  }
                </Col>
              </Row>
            }
            {subsidyCtrl.didi && (
              <Row>{messages('request.key641')/*参与人各自用车*/}</Row>
            )}
          </Form>
        </Modal>
        <Modal title={messages('request.key222'/*预算校验*/)}
          visible={budgeting}
        >
          <Progress percent={percent} status="active" />
          <p>{messages('request.key223'/*正在校验...*/)}</p>
        </Modal>
        <Modal title={messages('request.key563')/*注意*/} visible={userInfoCheckVisible} onCancel={this.closeUserCheckModal} maskClosable={false} destroyOnClose={true}
          footer={[
            <Button key="submit" onClick={() => this.handleUserCheckModal('submit')}>{messages('request.key180')/*继续提交*/}</Button>,
            <Button key="save" type="primary" onClick={() => this.handleUserCheckModal('save')}>{messages('common.save.only')/*仅保存*/}</Button>
          ]}
        >
          <div>
            <div>{messages('request.key564')/*单据包含国际行程，以下人员尚未维护完整的护照信息，可能影响预定，是否继续？*/}</div>
            <div style={{ margin: '20px 0', fontSize: '16px', color: '#0A0F1E' }}>{userCheckResult}</div>
            <div style={{ backgroundColor: '#F2F7FB', color: '#5F78A5' }}>Tips: {messages('request.key565')/*可先保存单据，在人员信息或通过管理员维护好护照信息后再来提交差旅申请单。*/}</div>
          </div>
        </Modal>
      </div>
    )
  }
}

NewRequest.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    enableDepCompany: state.setting.enableDepCompany,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser,
    language: state.main.language,
    profile: state.login.profile
  }
}

const wrappedNewRequest = Form.create(
  {
    onValuesChange(props, values) {
      newRequestThis.formItemChange(values);
    },
  }
)(NewRequest);

export default connect(mapStateToProps)(wrappedNewRequest)
